code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" SCREAMING_SNAKE_CASE : dict[str, float] = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.6_02_17_66_34e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.3_5_5_8_1_8, } def __UpperCAmelCase ( snake_case_ : str , snake_case_ : str , snake_case_ : float ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: _lowerCAmelCase = ( F"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" F"""Valid values are: {", ".join(snake_case_ )}""" ) raise ValueError(snake_case_ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
361
"""simple docstring""" import math def __UpperCAmelCase ( snake_case_ : int ) -> list[int]: """simple docstring""" _lowerCAmelCase = [] _lowerCAmelCase = 2 _lowerCAmelCase = int(math.sqrt(snake_case_ ) ) # Size of every segment _lowerCAmelCase = [True] * (end + 1) _lowerCAmelCase = [] while start <= end: if temp[start] is True: in_prime.append(snake_case_ ) for i in range(start * start , end + 1 , snake_case_ ): _lowerCAmelCase = False start += 1 prime += in_prime _lowerCAmelCase = end + 1 _lowerCAmelCase = min(2 * end , snake_case_ ) while low <= n: _lowerCAmelCase = [True] * (high - low + 1) for each in in_prime: _lowerCAmelCase = math.floor(low / each ) * each if t < low: t += each for j in range(snake_case_ , high + 1 , snake_case_ ): _lowerCAmelCase = False for j in range(len(snake_case_ ) ): if temp[j] is True: prime.append(j + low ) _lowerCAmelCase = high + 1 _lowerCAmelCase = min(high + end , snake_case_ ) return prime print(sieve(1_0**6))
317
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): @slow def A__ (self ): '''simple docstring''' _lowerCAmelCase = TFAutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" ) _lowerCAmelCase = AutoTokenizer.from_pretrained("""google/mt5-small""" ) _lowerCAmelCase = tokenizer("""Hello there""" , return_tensors="""tf""" ).input_ids _lowerCAmelCase = tokenizer("""Hi I am""" , return_tensors="""tf""" ).input_ids _lowerCAmelCase = model(lowerCamelCase , labels=lowerCamelCase ).loss _lowerCAmelCase = -tf.math.reduce_mean(lowerCamelCase ).numpy() _lowerCAmelCase = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
362
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters SCREAMING_SNAKE_CASE : Any = (7_2_0, 1_2_8_0) # Height, Width SCREAMING_SNAKE_CASE : List[str] = (0.4, 0.6) # if height or width lower than this scale, drop it. SCREAMING_SNAKE_CASE : List[Any] = 1 / 1_0_0 SCREAMING_SNAKE_CASE : Optional[Any] = '''''' SCREAMING_SNAKE_CASE : Dict = '''''' SCREAMING_SNAKE_CASE : List[Any] = '''''' SCREAMING_SNAKE_CASE : Dict = 2_5_0 def __UpperCAmelCase ( ) -> None: """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = get_dataset(snake_case_ , snake_case_ ) for index in range(snake_case_ ): _lowerCAmelCase = random.sample(range(len(snake_case_ ) ) , 4 ) _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = update_image_and_anno( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , filter_scale=snake_case_ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' _lowerCAmelCase = random_chars(32 ) _lowerCAmelCase = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] _lowerCAmelCase = F"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(F"""{file_root}.jpg""" , snake_case_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) _lowerCAmelCase = [] for anno in new_annos: _lowerCAmelCase = anno[3] - anno[1] _lowerCAmelCase = anno[4] - anno[2] _lowerCAmelCase = anno[1] + width / 2 _lowerCAmelCase = anno[2] + height / 2 _lowerCAmelCase = F"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(snake_case_ ) with open(F"""{file_root}.txt""" , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __UpperCAmelCase ( snake_case_ : str , snake_case_ : str ) -> tuple[list, list]: """simple docstring""" _lowerCAmelCase = [] _lowerCAmelCase = [] for label_file in glob.glob(os.path.join(snake_case_ , """*.txt""" ) ): _lowerCAmelCase = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(snake_case_ ) as in_file: _lowerCAmelCase = in_file.readlines() _lowerCAmelCase = os.path.join(snake_case_ , F"""{label_name}.jpg""" ) _lowerCAmelCase = [] for obj_list in obj_lists: _lowerCAmelCase = obj_list.rstrip("""\n""" ).split(""" """ ) _lowerCAmelCase = float(obj[1] ) - float(obj[3] ) / 2 _lowerCAmelCase = float(obj[2] ) - float(obj[4] ) / 2 _lowerCAmelCase = float(obj[1] ) + float(obj[3] ) / 2 _lowerCAmelCase = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(snake_case_ ) labels.append(snake_case_ ) return img_paths, labels def __UpperCAmelCase ( snake_case_ : list , snake_case_ : list , snake_case_ : list[int] , snake_case_ : tuple[int, int] , snake_case_ : tuple[float, float] , snake_case_ : float = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" _lowerCAmelCase = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) _lowerCAmelCase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _lowerCAmelCase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) _lowerCAmelCase = int(scale_x * output_size[1] ) _lowerCAmelCase = int(scale_y * output_size[0] ) _lowerCAmelCase = [] _lowerCAmelCase = [] for i, index in enumerate(snake_case_ ): _lowerCAmelCase = all_img_list[index] path_list.append(snake_case_ ) _lowerCAmelCase = all_annos[index] _lowerCAmelCase = cva.imread(snake_case_ ) if i == 0: # top-left _lowerCAmelCase = cva.resize(snake_case_ , (divid_point_x, divid_point_y) ) _lowerCAmelCase = img for bbox in img_annos: _lowerCAmelCase = bbox[1] * scale_x _lowerCAmelCase = bbox[2] * scale_y _lowerCAmelCase = bbox[3] * scale_x _lowerCAmelCase = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right _lowerCAmelCase = cva.resize(snake_case_ , (output_size[1] - divid_point_x, divid_point_y) ) _lowerCAmelCase = img for bbox in img_annos: _lowerCAmelCase = scale_x + bbox[1] * (1 - scale_x) _lowerCAmelCase = bbox[2] * scale_y _lowerCAmelCase = scale_x + bbox[3] * (1 - scale_x) _lowerCAmelCase = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left _lowerCAmelCase = cva.resize(snake_case_ , (divid_point_x, output_size[0] - divid_point_y) ) _lowerCAmelCase = img for bbox in img_annos: _lowerCAmelCase = bbox[1] * scale_x _lowerCAmelCase = scale_y + bbox[2] * (1 - scale_y) _lowerCAmelCase = bbox[3] * scale_x _lowerCAmelCase = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right _lowerCAmelCase = cva.resize( snake_case_ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) _lowerCAmelCase = img for bbox in img_annos: _lowerCAmelCase = scale_x + bbox[1] * (1 - scale_x) _lowerCAmelCase = scale_y + bbox[2] * (1 - scale_y) _lowerCAmelCase = scale_x + bbox[3] * (1 - scale_x) _lowerCAmelCase = 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: _lowerCAmelCase = [ 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 __UpperCAmelCase ( snake_case_ : int ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" _lowerCAmelCase = ascii_lowercase + digits return "".join(random.choice(snake_case_ ) for _ in range(snake_case_ ) ) if __name__ == "__main__": main() print('''DONE ✅''')
317
0
"""simple docstring""" def __UpperCAmelCase ( snake_case_ : Optional[int] , snake_case_ : Any , snake_case_ : int=False ) -> Dict: """simple docstring""" if isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ): _lowerCAmelCase = len(set_a.intersection(snake_case_ ) ) if alternative_union: _lowerCAmelCase = len(snake_case_ ) + len(snake_case_ ) else: _lowerCAmelCase = len(set_a.union(snake_case_ ) ) return intersection / union if isinstance(snake_case_ , (list, tuple) ) and isinstance(snake_case_ , (list, tuple) ): _lowerCAmelCase = [element for element in set_a if element in set_b] if alternative_union: _lowerCAmelCase = len(snake_case_ ) + len(snake_case_ ) return len(snake_case_ ) / union else: _lowerCAmelCase = set_a + [element for element in set_b if element not in set_a] return len(snake_case_ ) / len(snake_case_ ) return len(snake_case_ ) / len(snake_case_ ) return None if __name__ == "__main__": SCREAMING_SNAKE_CASE : int = {'''a''', '''b''', '''c''', '''d''', '''e'''} SCREAMING_SNAKE_CASE : Union[str, Any] = {'''c''', '''d''', '''e''', '''f''', '''h''', '''i'''} print(jaccard_similarity(set_a, set_b))
363
"""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. SCREAMING_SNAKE_CASE : 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 __UpperCAmelCase ( snake_case_ : Optional[int] ) -> List[str]: """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(snake_case_ ) def __UpperCAmelCase ( snake_case_ : Union[str, Any] ) -> int: """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main _lowerCAmelCase = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(snake_case_ , id=snake_case_ )
317
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __UpperCAmelCase ( snake_case_ : List[Any] ) -> List[str]: """simple docstring""" _lowerCAmelCase = [2, 2, 6, 2] if """tiny""" in model_name else [2, 2, 18, 2] _lowerCAmelCase = True if """large""" in model_name or """huge""" in model_name else False _lowerCAmelCase = True if """large""" in model_name or """huge""" in model_name else False _lowerCAmelCase = True if """large""" in model_name or """huge""" in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: _lowerCAmelCase = [3, 3, 3, 3] _lowerCAmelCase = [5, 5, 5, 5] elif "fl4" in model_name: _lowerCAmelCase = [4, 4, 4, 4] _lowerCAmelCase = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: _lowerCAmelCase = [3, 3, 3, 3] if "lrf" in model_name: _lowerCAmelCase = [3, 3, 3, 3] else: _lowerCAmelCase = [2, 2, 2, 2] if "tiny" in model_name: _lowerCAmelCase = 96 elif "small" in model_name: _lowerCAmelCase = 96 elif "base" in model_name: _lowerCAmelCase = 128 elif "large" in model_name: _lowerCAmelCase = 192 elif "xlarge" in model_name: _lowerCAmelCase = 256 elif "huge" in model_name: _lowerCAmelCase = 352 # set label information _lowerCAmelCase = """huggingface/label-files""" if "large" in model_name or "huge" in model_name: _lowerCAmelCase = """imagenet-22k-id2label.json""" else: _lowerCAmelCase = """imagenet-1k-id2label.json""" _lowerCAmelCase = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="""dataset""" ) , """r""" ) ) _lowerCAmelCase = {int(snake_case_ ): v for k, v in idalabel.items()} _lowerCAmelCase = {v: k for k, v in idalabel.items()} _lowerCAmelCase = FocalNetConfig( embed_dim=snake_case_ , depths=snake_case_ , focal_levels=snake_case_ , focal_windows=snake_case_ , use_conv_embed=snake_case_ , idalabel=snake_case_ , labelaid=snake_case_ , use_post_layernorm=snake_case_ , use_layerscale=snake_case_ , ) return config def __UpperCAmelCase ( snake_case_ : Optional[int] ) -> Any: """simple docstring""" if "patch_embed.proj" in name: _lowerCAmelCase = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: _lowerCAmelCase = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: _lowerCAmelCase = """encoder.""" + name if "encoder.layers" in name: _lowerCAmelCase = name.replace("""encoder.layers""" , """encoder.stages""" ) if "downsample.proj" in name: _lowerCAmelCase = name.replace("""downsample.proj""" , """downsample.projection""" ) if "blocks" in name: _lowerCAmelCase = name.replace("""blocks""" , """layers""" ) if "modulation.f.weight" in name or "modulation.f.bias" in name: _lowerCAmelCase = name.replace("""modulation.f""" , """modulation.projection_in""" ) if "modulation.h.weight" in name or "modulation.h.bias" in name: _lowerCAmelCase = name.replace("""modulation.h""" , """modulation.projection_context""" ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: _lowerCAmelCase = name.replace("""modulation.proj""" , """modulation.projection_out""" ) if name == "norm.weight": _lowerCAmelCase = """layernorm.weight""" if name == "norm.bias": _lowerCAmelCase = """layernorm.bias""" if "head" in name: _lowerCAmelCase = name.replace("""head""" , """classifier""" ) else: _lowerCAmelCase = """focalnet.""" + name return name def __UpperCAmelCase ( snake_case_ : Any , snake_case_ : Tuple , snake_case_ : List[str]=False ) -> int: """simple docstring""" _lowerCAmelCase = { """focalnet-tiny""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth""", """focalnet-tiny-lrf""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth""", """focalnet-small""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth""", """focalnet-small-lrf""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth""", """focalnet-base""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth""", """focalnet-base-lrf""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth""", """focalnet-large-lrf-fl3""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth""", """focalnet-large-lrf-fl4""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth""", """focalnet-xlarge-lrf-fl3""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth""", """focalnet-xlarge-lrf-fl4""": """https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth""", } # fmt: on _lowerCAmelCase = model_name_to_url[model_name] print("""Checkpoint URL: """ , snake_case_ ) _lowerCAmelCase = torch.hub.load_state_dict_from_url(snake_case_ , map_location="""cpu""" )["""model"""] # rename keys for key in state_dict.copy().keys(): _lowerCAmelCase = state_dict.pop(snake_case_ ) _lowerCAmelCase = val _lowerCAmelCase = get_focalnet_config(snake_case_ ) _lowerCAmelCase = FocalNetForImageClassification(snake_case_ ) model.eval() # load state dict model.load_state_dict(snake_case_ ) # verify conversion _lowerCAmelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" _lowerCAmelCase = BitImageProcessor( do_resize=snake_case_ , size={"""shortest_edge""": 256} , resample=PILImageResampling.BILINEAR , do_center_crop=snake_case_ , crop_size=224 , do_normalize=snake_case_ , image_mean=snake_case_ , image_std=snake_case_ , ) _lowerCAmelCase = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) _lowerCAmelCase = processor(images=snake_case_ , return_tensors="""pt""" ) _lowerCAmelCase = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6] , std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) _lowerCAmelCase = image_transforms(snake_case_ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , snake_case_ , atol=1e-4 ) _lowerCAmelCase = model(**snake_case_ ) _lowerCAmelCase = outputs.logits.argmax(-1 ).item() print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] ) print("""First values of logits:""" , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": _lowerCAmelCase = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": _lowerCAmelCase = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": _lowerCAmelCase = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": _lowerCAmelCase = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": _lowerCAmelCase = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": _lowerCAmelCase = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(F"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(F"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(F"""{model_name}""" ) processor.push_to_hub(F"""{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''focalnet-tiny''', type=str, help='''Name of the FocalNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub.''', ) SCREAMING_SNAKE_CASE : Tuple = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
364
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool SCREAMING_SNAKE_CASE : Optional[Any] = { '''Acehnese Arabic''': '''ace_Arab''', '''Acehnese Latin''': '''ace_Latn''', '''Mesopotamian Arabic''': '''acm_Arab''', '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''', '''Tunisian Arabic''': '''aeb_Arab''', '''Afrikaans''': '''afr_Latn''', '''South Levantine Arabic''': '''ajp_Arab''', '''Akan''': '''aka_Latn''', '''Amharic''': '''amh_Ethi''', '''North Levantine Arabic''': '''apc_Arab''', '''Modern Standard Arabic''': '''arb_Arab''', '''Modern Standard Arabic Romanized''': '''arb_Latn''', '''Najdi Arabic''': '''ars_Arab''', '''Moroccan Arabic''': '''ary_Arab''', '''Egyptian Arabic''': '''arz_Arab''', '''Assamese''': '''asm_Beng''', '''Asturian''': '''ast_Latn''', '''Awadhi''': '''awa_Deva''', '''Central Aymara''': '''ayr_Latn''', '''South Azerbaijani''': '''azb_Arab''', '''North Azerbaijani''': '''azj_Latn''', '''Bashkir''': '''bak_Cyrl''', '''Bambara''': '''bam_Latn''', '''Balinese''': '''ban_Latn''', '''Belarusian''': '''bel_Cyrl''', '''Bemba''': '''bem_Latn''', '''Bengali''': '''ben_Beng''', '''Bhojpuri''': '''bho_Deva''', '''Banjar Arabic''': '''bjn_Arab''', '''Banjar Latin''': '''bjn_Latn''', '''Standard Tibetan''': '''bod_Tibt''', '''Bosnian''': '''bos_Latn''', '''Buginese''': '''bug_Latn''', '''Bulgarian''': '''bul_Cyrl''', '''Catalan''': '''cat_Latn''', '''Cebuano''': '''ceb_Latn''', '''Czech''': '''ces_Latn''', '''Chokwe''': '''cjk_Latn''', '''Central Kurdish''': '''ckb_Arab''', '''Crimean Tatar''': '''crh_Latn''', '''Welsh''': '''cym_Latn''', '''Danish''': '''dan_Latn''', '''German''': '''deu_Latn''', '''Southwestern Dinka''': '''dik_Latn''', '''Dyula''': '''dyu_Latn''', '''Dzongkha''': '''dzo_Tibt''', '''Greek''': '''ell_Grek''', '''English''': '''eng_Latn''', '''Esperanto''': '''epo_Latn''', '''Estonian''': '''est_Latn''', '''Basque''': '''eus_Latn''', '''Ewe''': '''ewe_Latn''', '''Faroese''': '''fao_Latn''', '''Fijian''': '''fij_Latn''', '''Finnish''': '''fin_Latn''', '''Fon''': '''fon_Latn''', '''French''': '''fra_Latn''', '''Friulian''': '''fur_Latn''', '''Nigerian Fulfulde''': '''fuv_Latn''', '''Scottish Gaelic''': '''gla_Latn''', '''Irish''': '''gle_Latn''', '''Galician''': '''glg_Latn''', '''Guarani''': '''grn_Latn''', '''Gujarati''': '''guj_Gujr''', '''Haitian Creole''': '''hat_Latn''', '''Hausa''': '''hau_Latn''', '''Hebrew''': '''heb_Hebr''', '''Hindi''': '''hin_Deva''', '''Chhattisgarhi''': '''hne_Deva''', '''Croatian''': '''hrv_Latn''', '''Hungarian''': '''hun_Latn''', '''Armenian''': '''hye_Armn''', '''Igbo''': '''ibo_Latn''', '''Ilocano''': '''ilo_Latn''', '''Indonesian''': '''ind_Latn''', '''Icelandic''': '''isl_Latn''', '''Italian''': '''ita_Latn''', '''Javanese''': '''jav_Latn''', '''Japanese''': '''jpn_Jpan''', '''Kabyle''': '''kab_Latn''', '''Jingpho''': '''kac_Latn''', '''Kamba''': '''kam_Latn''', '''Kannada''': '''kan_Knda''', '''Kashmiri Arabic''': '''kas_Arab''', '''Kashmiri Devanagari''': '''kas_Deva''', '''Georgian''': '''kat_Geor''', '''Central Kanuri Arabic''': '''knc_Arab''', '''Central Kanuri Latin''': '''knc_Latn''', '''Kazakh''': '''kaz_Cyrl''', '''Kabiyè''': '''kbp_Latn''', '''Kabuverdianu''': '''kea_Latn''', '''Khmer''': '''khm_Khmr''', '''Kikuyu''': '''kik_Latn''', '''Kinyarwanda''': '''kin_Latn''', '''Kyrgyz''': '''kir_Cyrl''', '''Kimbundu''': '''kmb_Latn''', '''Northern Kurdish''': '''kmr_Latn''', '''Kikongo''': '''kon_Latn''', '''Korean''': '''kor_Hang''', '''Lao''': '''lao_Laoo''', '''Ligurian''': '''lij_Latn''', '''Limburgish''': '''lim_Latn''', '''Lingala''': '''lin_Latn''', '''Lithuanian''': '''lit_Latn''', '''Lombard''': '''lmo_Latn''', '''Latgalian''': '''ltg_Latn''', '''Luxembourgish''': '''ltz_Latn''', '''Luba-Kasai''': '''lua_Latn''', '''Ganda''': '''lug_Latn''', '''Luo''': '''luo_Latn''', '''Mizo''': '''lus_Latn''', '''Standard Latvian''': '''lvs_Latn''', '''Magahi''': '''mag_Deva''', '''Maithili''': '''mai_Deva''', '''Malayalam''': '''mal_Mlym''', '''Marathi''': '''mar_Deva''', '''Minangkabau Arabic ''': '''min_Arab''', '''Minangkabau Latin''': '''min_Latn''', '''Macedonian''': '''mkd_Cyrl''', '''Plateau Malagasy''': '''plt_Latn''', '''Maltese''': '''mlt_Latn''', '''Meitei Bengali''': '''mni_Beng''', '''Halh Mongolian''': '''khk_Cyrl''', '''Mossi''': '''mos_Latn''', '''Maori''': '''mri_Latn''', '''Burmese''': '''mya_Mymr''', '''Dutch''': '''nld_Latn''', '''Norwegian Nynorsk''': '''nno_Latn''', '''Norwegian Bokmål''': '''nob_Latn''', '''Nepali''': '''npi_Deva''', '''Northern Sotho''': '''nso_Latn''', '''Nuer''': '''nus_Latn''', '''Nyanja''': '''nya_Latn''', '''Occitan''': '''oci_Latn''', '''West Central Oromo''': '''gaz_Latn''', '''Odia''': '''ory_Orya''', '''Pangasinan''': '''pag_Latn''', '''Eastern Panjabi''': '''pan_Guru''', '''Papiamento''': '''pap_Latn''', '''Western Persian''': '''pes_Arab''', '''Polish''': '''pol_Latn''', '''Portuguese''': '''por_Latn''', '''Dari''': '''prs_Arab''', '''Southern Pashto''': '''pbt_Arab''', '''Ayacucho Quechua''': '''quy_Latn''', '''Romanian''': '''ron_Latn''', '''Rundi''': '''run_Latn''', '''Russian''': '''rus_Cyrl''', '''Sango''': '''sag_Latn''', '''Sanskrit''': '''san_Deva''', '''Santali''': '''sat_Olck''', '''Sicilian''': '''scn_Latn''', '''Shan''': '''shn_Mymr''', '''Sinhala''': '''sin_Sinh''', '''Slovak''': '''slk_Latn''', '''Slovenian''': '''slv_Latn''', '''Samoan''': '''smo_Latn''', '''Shona''': '''sna_Latn''', '''Sindhi''': '''snd_Arab''', '''Somali''': '''som_Latn''', '''Southern Sotho''': '''sot_Latn''', '''Spanish''': '''spa_Latn''', '''Tosk Albanian''': '''als_Latn''', '''Sardinian''': '''srd_Latn''', '''Serbian''': '''srp_Cyrl''', '''Swati''': '''ssw_Latn''', '''Sundanese''': '''sun_Latn''', '''Swedish''': '''swe_Latn''', '''Swahili''': '''swh_Latn''', '''Silesian''': '''szl_Latn''', '''Tamil''': '''tam_Taml''', '''Tatar''': '''tat_Cyrl''', '''Telugu''': '''tel_Telu''', '''Tajik''': '''tgk_Cyrl''', '''Tagalog''': '''tgl_Latn''', '''Thai''': '''tha_Thai''', '''Tigrinya''': '''tir_Ethi''', '''Tamasheq Latin''': '''taq_Latn''', '''Tamasheq Tifinagh''': '''taq_Tfng''', '''Tok Pisin''': '''tpi_Latn''', '''Tswana''': '''tsn_Latn''', '''Tsonga''': '''tso_Latn''', '''Turkmen''': '''tuk_Latn''', '''Tumbuka''': '''tum_Latn''', '''Turkish''': '''tur_Latn''', '''Twi''': '''twi_Latn''', '''Central Atlas Tamazight''': '''tzm_Tfng''', '''Uyghur''': '''uig_Arab''', '''Ukrainian''': '''ukr_Cyrl''', '''Umbundu''': '''umb_Latn''', '''Urdu''': '''urd_Arab''', '''Northern Uzbek''': '''uzn_Latn''', '''Venetian''': '''vec_Latn''', '''Vietnamese''': '''vie_Latn''', '''Waray''': '''war_Latn''', '''Wolof''': '''wol_Latn''', '''Xhosa''': '''xho_Latn''', '''Eastern Yiddish''': '''ydd_Hebr''', '''Yoruba''': '''yor_Latn''', '''Yue Chinese''': '''yue_Hant''', '''Chinese Simplified''': '''zho_Hans''', '''Chinese Traditional''': '''zho_Hant''', '''Standard Malay''': '''zsm_Latn''', '''Zulu''': '''zul_Latn''', } class __lowerCamelCase ( __lowercase ): __UpperCamelCase = 'facebook/nllb-200-distilled-600M' __UpperCamelCase = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) __UpperCamelCase = 'translator' __UpperCamelCase = AutoTokenizer __UpperCamelCase = AutoModelForSeqaSeqLM __UpperCamelCase = LANGUAGE_CODES __UpperCamelCase = ['text', 'text', 'text'] __UpperCamelCase = ['text'] def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) _lowerCAmelCase = self.lang_to_code[src_lang] _lowerCAmelCase = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( lowerCamelCase , return_tensors="""pt""" , src_lang=lowerCamelCase , tgt_lang=lowerCamelCase ) def A__ (self , lowerCamelCase ): '''simple docstring''' return self.model.generate(**lowerCamelCase ) def A__ (self , lowerCamelCase ): '''simple docstring''' return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=lowerCamelCase )
317
0
"""simple docstring""" import math from datetime import datetime, timedelta def __UpperCAmelCase ( snake_case_ : int ) -> datetime: """simple docstring""" _lowerCAmelCase = year % 19 _lowerCAmelCase = year % 4 _lowerCAmelCase = year % 7 _lowerCAmelCase = math.floor(year / 100 ) _lowerCAmelCase = math.floor((13 + 8 * leap_day_inhibits) / 25 ) _lowerCAmelCase = leap_day_inhibits / 4 _lowerCAmelCase = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 _lowerCAmelCase = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 _lowerCAmelCase = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon _lowerCAmelCase = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(snake_case_ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(snake_case_ , 4 , 18 ) else: return datetime(snake_case_ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): SCREAMING_SNAKE_CASE : Dict = '''will be''' if year > datetime.now().year else '''was''' print(F'Easter in {year} {tense} {gauss_easter(year)}')
365
"""simple docstring""" from math import isqrt def __UpperCAmelCase ( snake_case_ : int ) -> list[int]: """simple docstring""" _lowerCAmelCase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , snake_case_ , snake_case_ ): _lowerCAmelCase = False return [i for i in range(2 , snake_case_ ) if is_prime[i]] def __UpperCAmelCase ( snake_case_ : int = 10**8 ) -> int: """simple docstring""" _lowerCAmelCase = calculate_prime_numbers(max_number // 2 ) _lowerCAmelCase = 0 _lowerCAmelCase = 0 _lowerCAmelCase = len(snake_case_ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'{solution() = }')
317
0
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( """files""" , [ ["""full:README.md""", """dataset_infos.json"""], ["""empty:README.md""", """dataset_infos.json"""], ["""dataset_infos.json"""], ["""full:README.md"""], ] , ) def __UpperCAmelCase ( snake_case_ : Any , snake_case_ : Optional[Any] ): """simple docstring""" _lowerCAmelCase = tmp_path_factory.mktemp("""dset_infos_dir""" ) if "full:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""---\ndataset_info:\n dataset_size: 42\n---""" ) if "empty:README.md" in files: with open(dataset_infos_dir / """README.md""" , """w""" ) as f: f.write("""""" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f: f.write("""{\"default\": {\"dataset_size\": 42}}""" ) _lowerCAmelCase = DatasetInfosDict.from_directory(snake_case_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( """dataset_info""" , [ DatasetInfo(), DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ), ] , ) def __UpperCAmelCase ( snake_case_ : Optional[int] , snake_case_ : DatasetInfo ): """simple docstring""" _lowerCAmelCase = str(snake_case_ ) dataset_info.write_to_directory(snake_case_ ) _lowerCAmelCase = DatasetInfo.from_directory(snake_case_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(snake_case_ , """dataset_info.json""" ) ) def __UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = DatasetInfo( description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) _lowerCAmelCase = dataset_info._to_yaml_dict() assert sorted(snake_case_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _lowerCAmelCase = yaml.safe_dump(snake_case_ ) _lowerCAmelCase = yaml.safe_load(snake_case_ ) assert dataset_info_yaml_dict == reloaded def __UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = DatasetInfo() _lowerCAmelCase = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( """dataset_infos_dict""" , [ DatasetInfosDict(), DatasetInfosDict({"""default""": DatasetInfo()} ), DatasetInfosDict({"""my_config_name""": DatasetInfo()} ), DatasetInfosDict( { """default""": DatasetInfo( description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ) } ), DatasetInfosDict( { """v1""": DatasetInfo(dataset_size=42 ), """v2""": DatasetInfo(dataset_size=1337 ), } ), ] , ) def __UpperCAmelCase ( snake_case_ : Dict , snake_case_ : DatasetInfosDict ): """simple docstring""" _lowerCAmelCase = str(snake_case_ ) dataset_infos_dict.write_to_directory(snake_case_ ) _lowerCAmelCase = DatasetInfosDict.from_directory(snake_case_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _lowerCAmelCase = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _lowerCAmelCase = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(snake_case_ , """README.md""" ) )
366
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class __lowerCamelCase ( __lowercase ): __UpperCamelCase = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) __UpperCamelCase = 'CIDAS/clipseg-rd64-refined' __UpperCamelCase = 'image_segmenter' __UpperCamelCase = CLIPSegForImageSegmentation __UpperCamelCase = ['image', 'text'] __UpperCamelCase = ['image'] def __init__(self , *lowerCamelCase , **lowerCamelCase ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*lowerCamelCase , **lowerCamelCase ) def A__ (self , lowerCamelCase , lowerCamelCase ): '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=lowerCamelCase , return_tensors="""pt""" ) def A__ (self , lowerCamelCase ): '''simple docstring''' with torch.no_grad(): _lowerCAmelCase = self.model(**lowerCamelCase ).logits return logits def A__ (self , lowerCamelCase ): '''simple docstring''' _lowerCAmelCase = outputs.cpu().detach().numpy() _lowerCAmelCase = 0 _lowerCAmelCase = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
317
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) SCREAMING_SNAKE_CASE : Any = { '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : List[str] = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : Any = [ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
367
"""simple docstring""" from __future__ import annotations import queue class __lowerCamelCase : def __init__(self , lowerCamelCase ): '''simple docstring''' _lowerCAmelCase = data _lowerCAmelCase = None _lowerCAmelCase = None def __UpperCAmelCase ( ) -> TreeNode: """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCAmelCase = input("""Enter the value of the root node: """ ).strip().lower() _lowerCAmelCase = queue.Queue() _lowerCAmelCase = TreeNode(int(snake_case_ ) ) q.put(snake_case_ ) while not q.empty(): _lowerCAmelCase = q.get() _lowerCAmelCase = F"""Enter the left node of {node_found.data}: """ _lowerCAmelCase = input(snake_case_ ).strip().lower() or """n""" if check == "n": return tree_node _lowerCAmelCase = TreeNode(int(snake_case_ ) ) _lowerCAmelCase = left_node q.put(snake_case_ ) _lowerCAmelCase = F"""Enter the right node of {node_found.data}: """ _lowerCAmelCase = input(snake_case_ ).strip().lower() or """n""" if check == "n": return tree_node _lowerCAmelCase = TreeNode(int(snake_case_ ) ) _lowerCAmelCase = right_node q.put(snake_case_ ) raise def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return _lowerCAmelCase = queue.Queue() q.put(snake_case_ ) while not q.empty(): _lowerCAmelCase = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return _lowerCAmelCase = queue.Queue() q.put(snake_case_ ) while not q.empty(): _lowerCAmelCase = [] while not q.empty(): _lowerCAmelCase = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(snake_case_ ) def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return _lowerCAmelCase = [] _lowerCAmelCase = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(snake_case_ ) _lowerCAmelCase = n.left # end of while means current node doesn't have left child _lowerCAmelCase = stack.pop() # start to traverse its right child _lowerCAmelCase = n.right def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return _lowerCAmelCase = [] _lowerCAmelCase = node while n or stack: while n: stack.append(snake_case_ ) _lowerCAmelCase = n.left _lowerCAmelCase = stack.pop() print(n.data , end=""",""" ) _lowerCAmelCase = n.right def __UpperCAmelCase ( snake_case_ : TreeNode ) -> None: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not node: return _lowerCAmelCase , _lowerCAmelCase = [], [] _lowerCAmelCase = node stacka.append(snake_case_ ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCAmelCase = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(snake_case_ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def __UpperCAmelCase ( snake_case_ : str = "" , snake_case_ : int=50 , snake_case_ : Dict="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char _lowerCAmelCase , _lowerCAmelCase = divmod(width - len(snake_case_ ) - 2 , 2 ) return F"""{left * char} {s} {(left + extra) * char}""" if __name__ == "__main__": import doctest doctest.testmod() print(prompt('''Binary Tree Traversals''')) SCREAMING_SNAKE_CASE : TreeNode = build_tree() print(prompt('''Pre Order Traversal''')) pre_order(node) print(prompt() + '''\n''') print(prompt('''In Order Traversal''')) in_order(node) print(prompt() + '''\n''') print(prompt('''Post Order Traversal''')) post_order(node) print(prompt() + '''\n''') print(prompt('''Level Order Traversal''')) level_order(node) print(prompt() + '''\n''') print(prompt('''Actual Level Order Traversal''')) level_order_actual(node) print('''*''' * 5_0 + '''\n''') print(prompt('''Pre Order Traversal - Iteration Version''')) pre_order_iter(node) print(prompt() + '''\n''') print(prompt('''In Order Traversal - Iteration Version''')) in_order_iter(node) print(prompt() + '''\n''') print(prompt('''Post Order Traversal - Iteration Version''')) post_order_iter(node) print(prompt())
317
0
"""simple docstring""" def __UpperCAmelCase ( snake_case_ : str , snake_case_ : Any ) -> Optional[int]: """simple docstring""" _lowerCAmelCase = """""" for i in table: res += inp[i - 1] return res def __UpperCAmelCase ( snake_case_ : str ) -> Tuple: """simple docstring""" return data[1:] + data[0] def __UpperCAmelCase ( snake_case_ : int , snake_case_ : int ) -> Any: """simple docstring""" _lowerCAmelCase = """""" for i in range(len(snake_case_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def __UpperCAmelCase ( snake_case_ : Optional[int] , snake_case_ : str ) -> List[str]: """simple docstring""" _lowerCAmelCase = int("""0b""" + data[0] + data[-1] , 2 ) _lowerCAmelCase = int("""0b""" + data[1:3] , 2 ) return bin(s[row][col] )[2:] def __UpperCAmelCase ( snake_case_ : Optional[int] , snake_case_ : List[str] , snake_case_ : Union[str, Any] , snake_case_ : Tuple , snake_case_ : Dict ) -> str: """simple docstring""" _lowerCAmelCase = message[:4] _lowerCAmelCase = message[4:] _lowerCAmelCase = apply_table(snake_case_ , snake_case_ ) _lowerCAmelCase = xor(snake_case_ , snake_case_ ) _lowerCAmelCase = apply_sbox(snake_case_ , temp[:4] ) # noqa: E741 _lowerCAmelCase = apply_sbox(snake_case_ , temp[4:] ) _lowerCAmelCase = """0""" * (2 - len(snake_case_ )) + l # noqa: E741 _lowerCAmelCase = """0""" * (2 - len(snake_case_ )) + r _lowerCAmelCase = apply_table(l + r , snake_case_ ) _lowerCAmelCase = xor(snake_case_ , snake_case_ ) return temp + right if __name__ == "__main__": SCREAMING_SNAKE_CASE : str = input('''Enter 10 bit key: ''') SCREAMING_SNAKE_CASE : Optional[int] = input('''Enter 8 bit message: ''') SCREAMING_SNAKE_CASE : str = [6, 3, 7, 4, 8, 5, 1_0, 9] SCREAMING_SNAKE_CASE : Optional[Any] = [3, 5, 2, 7, 4, 1_0, 1, 9, 8, 6] SCREAMING_SNAKE_CASE : str = [2, 4, 3, 1] SCREAMING_SNAKE_CASE : Tuple = [2, 6, 3, 1, 4, 8, 5, 7] SCREAMING_SNAKE_CASE : List[str] = [4, 1, 3, 5, 7, 2, 8, 6] SCREAMING_SNAKE_CASE : Union[str, Any] = [4, 1, 2, 3, 2, 3, 4, 1] SCREAMING_SNAKE_CASE : List[str] = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] SCREAMING_SNAKE_CASE : Any = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation SCREAMING_SNAKE_CASE : Dict = apply_table(key, paa_table) SCREAMING_SNAKE_CASE : Optional[int] = temp[:5] SCREAMING_SNAKE_CASE : str = temp[5:] SCREAMING_SNAKE_CASE : List[Any] = left_shift(left) SCREAMING_SNAKE_CASE : int = left_shift(right) SCREAMING_SNAKE_CASE : Optional[Any] = apply_table(left + right, pa_table) SCREAMING_SNAKE_CASE : int = left_shift(left) SCREAMING_SNAKE_CASE : Dict = left_shift(right) SCREAMING_SNAKE_CASE : int = left_shift(left) SCREAMING_SNAKE_CASE : str = left_shift(right) SCREAMING_SNAKE_CASE : Union[str, Any] = apply_table(left + right, pa_table) # encryption SCREAMING_SNAKE_CASE : int = apply_table(message, IP) SCREAMING_SNAKE_CASE : Optional[int] = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE : int = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE : Tuple = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE : List[str] = apply_table(temp, IP_inv) print('''Cipher text is:''', CT) # decryption SCREAMING_SNAKE_CASE : Dict = apply_table(CT, IP) SCREAMING_SNAKE_CASE : Optional[int] = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE : Optional[Any] = temp[4:] + temp[:4] SCREAMING_SNAKE_CASE : Tuple = function(expansion, sa, sa, keya, temp) SCREAMING_SNAKE_CASE : Optional[Any] = apply_table(temp, IP_inv) print('''Plain text after decypting is:''', PT)
368
"""simple docstring""" from __future__ import annotations class __lowerCamelCase : def __init__(self , lowerCamelCase , lowerCamelCase ): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase = text, pattern _lowerCAmelCase , _lowerCAmelCase = len(lowerCamelCase ), len(lowerCamelCase ) def A__ (self , lowerCamelCase ): '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def A__ (self , lowerCamelCase ): '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def A__ (self ): '''simple docstring''' _lowerCAmelCase = [] for i in range(self.textLen - self.patLen + 1 ): _lowerCAmelCase = self.mismatch_in_text(lowerCamelCase ) if mismatch_index == -1: positions.append(lowerCamelCase ) else: _lowerCAmelCase = self.match_in_pattern(self.text[mismatch_index] ) _lowerCAmelCase = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions SCREAMING_SNAKE_CASE : Any = '''ABAABA''' SCREAMING_SNAKE_CASE : Optional[int] = '''AB''' SCREAMING_SNAKE_CASE : str = BoyerMooreSearch(text, pattern) SCREAMING_SNAKE_CASE : Tuple = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
317
0
"""simple docstring""" from math import factorial SCREAMING_SNAKE_CASE : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def __UpperCAmelCase ( snake_case_ : int ) -> int: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ): raise TypeError("""Parameter number must be int""" ) if number < 0: raise ValueError("""Parameter number must be greater than or equal to 0""" ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(snake_case_ ) ) def __UpperCAmelCase ( snake_case_ : int = 60 , snake_case_ : int = 1000000 ) -> int: """simple docstring""" if not isinstance(snake_case_ , snake_case_ ) or not isinstance(snake_case_ , snake_case_ ): raise TypeError("""Parameters chain_length and number_limit must be int""" ) if chain_length <= 0 or number_limit <= 0: raise ValueError( """Parameters chain_length and number_limit must be greater than 0""" ) # the counter for the chains with the exact desired length _lowerCAmelCase = 0 # the cached sizes of the previous chains _lowerCAmelCase = {} for start_chain_element in range(1 , snake_case_ ): # The temporary set will contain the elements of the chain _lowerCAmelCase = set() _lowerCAmelCase = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. _lowerCAmelCase = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(snake_case_ ) chain_set_length += 1 _lowerCAmelCase = digit_factorial_sum(snake_case_ ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] _lowerCAmelCase = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'{solution()}')
369
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device SCREAMING_SNAKE_CASE : List[str] = False class __lowerCamelCase ( unittest.TestCase ): pass @slow @require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): def A__ (self ): '''simple docstring''' _lowerCAmelCase = VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) _lowerCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = pipe( image=lowerCamelCase , generator=lowerCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" , ).images _lowerCAmelCase = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _lowerCAmelCase = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
317
0
"""simple docstring""" import requests SCREAMING_SNAKE_CASE : int = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def __UpperCAmelCase ( snake_case_ : str ) -> None: """simple docstring""" _lowerCAmelCase = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["""articles"""] , 1 ): print(F"""{i}.) {article["title"]}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
370
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCamelCase ( __lowercase , unittest.TestCase ): __UpperCamelCase = DiTPipeline __UpperCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS __UpperCamelCase = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } __UpperCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS __UpperCamelCase = False def A__ (self ): '''simple docstring''' torch.manual_seed(0 ) _lowerCAmelCase = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=lowerCamelCase , activation_fn="""gelu-approximate""" , num_embeds_ada_norm=1_000 , norm_type="""ada_norm_zero""" , norm_elementwise_affine=lowerCamelCase , ) _lowerCAmelCase = AutoencoderKL() _lowerCAmelCase = DDIMScheduler() _lowerCAmelCase = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler} return components def A__ (self , lowerCamelCase , lowerCamelCase=0 ): '''simple docstring''' if str(lowerCamelCase ).startswith("""mps""" ): _lowerCAmelCase = torch.manual_seed(lowerCamelCase ) else: _lowerCAmelCase = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) _lowerCAmelCase = { """class_labels""": [1], """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def A__ (self ): '''simple docstring''' _lowerCAmelCase = """cpu""" _lowerCAmelCase = self.get_dummy_components() _lowerCAmelCase = self.pipeline_class(**lowerCamelCase ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) _lowerCAmelCase = self.get_dummy_inputs(lowerCamelCase ) _lowerCAmelCase = pipe(**lowerCamelCase ).images _lowerCAmelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) _lowerCAmelCase = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) _lowerCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase , 1e-3 ) def A__ (self ): '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=lowerCamelCase , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def A__ (self ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class __lowerCamelCase ( unittest.TestCase ): def A__ (self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ (self ): '''simple docstring''' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" ) pipe.to("""cuda""" ) _lowerCAmelCase = ["""vase""", """umbrella""", """white shark""", """white wolf"""] _lowerCAmelCase = pipe.get_label_ids(lowerCamelCase ) _lowerCAmelCase = pipe(lowerCamelCase , generator=lowerCamelCase , num_inference_steps=40 , output_type="""np""" ).images for word, image in zip(lowerCamelCase , lowerCamelCase ): _lowerCAmelCase = load_numpy( f"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy""" ) assert np.abs((expected_image - image).max() ) < 1e-2 def A__ (self ): '''simple docstring''' _lowerCAmelCase = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" ) _lowerCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("""cuda""" ) _lowerCAmelCase = ["""vase""", """umbrella"""] _lowerCAmelCase = pipe.get_label_ids(lowerCamelCase ) _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = pipe(lowerCamelCase , generator=lowerCamelCase , num_inference_steps=25 , output_type="""np""" ).images for word, image in zip(lowerCamelCase , lowerCamelCase ): _lowerCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" f"""/dit/{word}_512.npy""" ) assert np.abs((expected_image - image).max() ) < 1e-1
317
0
"""simple docstring""" import math import qiskit def __UpperCAmelCase ( snake_case_ : int = 1 , snake_case_ : int = 1 , snake_case_ : int = 1 ) -> qiskit.result.counts.Counts: """simple docstring""" if ( isinstance(snake_case_ , snake_case_ ) or isinstance(snake_case_ , snake_case_ ) or isinstance(snake_case_ , snake_case_ ) ): raise TypeError("""inputs must be integers.""" ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError("""inputs must be positive.""" ) if ( (math.floor(snake_case_ ) != input_a) or (math.floor(snake_case_ ) != input_a) or (math.floor(snake_case_ ) != carry_in) ): raise ValueError("""inputs must be exact integers.""" ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError("""inputs must be less or equal to 2.""" ) # build registers _lowerCAmelCase = qiskit.QuantumRegister(4 , """qr""" ) _lowerCAmelCase = qiskit.ClassicalRegister(2 , """cr""" ) # list the entries _lowerCAmelCase = [input_a, input_a, carry_in] _lowerCAmelCase = qiskit.QuantumCircuit(snake_case_ , snake_case_ ) for i in range(0 , 3 ): if entry[i] == 2: quantum_circuit.h(snake_case_ ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(snake_case_ ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(snake_case_ ) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate quantum_circuit.cx(0 , 1 ) quantum_circuit.ccx(1 , 2 , 3 ) quantum_circuit.cx(1 , 2 ) quantum_circuit.cx(0 , 1 ) quantum_circuit.measure([2, 3] , snake_case_ ) # measure the last two qbits _lowerCAmelCase = qiskit.Aer.get_backend("""aer_simulator""" ) _lowerCAmelCase = qiskit.execute(snake_case_ , snake_case_ , shots=1000 ) return job.result().get_counts(snake_case_ ) if __name__ == "__main__": print(F'Total sum count for state is: {quantum_full_adder(1, 1, 1)}')
371
"""simple docstring""" from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def __UpperCAmelCase ( snake_case_ : Union[str, Any] ) -> Dict: """simple docstring""" return getitem, k def __UpperCAmelCase ( snake_case_ : Dict , snake_case_ : Union[str, Any] ) -> List[Any]: """simple docstring""" return setitem, k, v def __UpperCAmelCase ( snake_case_ : str ) -> Optional[int]: """simple docstring""" return delitem, k def __UpperCAmelCase ( snake_case_ : Optional[Any] , snake_case_ : Tuple , *snake_case_ : Tuple ) -> str: """simple docstring""" try: return fun(snake_case_ , *snake_case_ ), None except Exception as e: return None, e SCREAMING_SNAKE_CASE : int = ( _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), ) SCREAMING_SNAKE_CASE : List[Any] = [ _set('''key_a''', '''val_a'''), _set('''key_a''', '''val_b'''), ] SCREAMING_SNAKE_CASE : Any = [ _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), _del('''key_a'''), _del('''key_b'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), ] SCREAMING_SNAKE_CASE : Union[str, Any] = [ _get('''key_a'''), _del('''key_a'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), _del('''key_a'''), _get('''key_a'''), ] SCREAMING_SNAKE_CASE : Optional[Any] = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] SCREAMING_SNAKE_CASE : Optional[int] = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('''key_a''', '''val_b'''), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def __UpperCAmelCase ( snake_case_ : List[Any] ) -> Tuple: """simple docstring""" _lowerCAmelCase = HashMap(initial_block_size=4 ) _lowerCAmelCase = {} for _, (fun, *args) in enumerate(snake_case_ ): _lowerCAmelCase , _lowerCAmelCase = _run_operation(snake_case_ , snake_case_ , *snake_case_ ) _lowerCAmelCase , _lowerCAmelCase = _run_operation(snake_case_ , snake_case_ , *snake_case_ ) assert my_res == py_res assert str(snake_case_ ) == str(snake_case_ ) assert set(snake_case_ ) == set(snake_case_ ) assert len(snake_case_ ) == len(snake_case_ ) assert set(my.items() ) == set(py.items() ) def __UpperCAmelCase ( ) -> Tuple: """simple docstring""" def is_public(snake_case_ : str ) -> bool: return not name.startswith("""_""" ) _lowerCAmelCase = {name for name in dir({} ) if is_public(snake_case_ )} _lowerCAmelCase = {name for name in dir(HashMap() ) if is_public(snake_case_ )} assert dict_public_names > hash_public_names
317
0
"""simple docstring""" def _A (__a ) -> int: """simple docstring""" if not isinstance(__a , __a ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) SCREAMING_SNAKE_CASE_ : int = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
318
"""simple docstring""" from scipy.stats import pearsonr import datasets UpperCAmelCase_ : List[Any] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ UpperCAmelCase_ : Optional[int] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ UpperCAmelCase_ : Tuple = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float'''), '''references''': datasets.Value('''float'''), }) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=False): '''simple docstring''' if return_pvalue: SCREAMING_SNAKE_CASE_ : int = pearsonr(lowercase_ , lowercase_) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(lowercase_ , lowercase_)[0])}
318
1
"""simple docstring""" def _A (__a = 10_00 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 2**power SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 while n: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
318
"""simple docstring""" import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class lowerCAmelCase__ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any , lowercase_ : Dict[str, int] , lowercase_ : List[str] , lowercase_ : int = None , lowercase_ : int = None): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : str = pad_token_id SCREAMING_SNAKE_CASE_ : Optional[int] = max_length SCREAMING_SNAKE_CASE_ : Dict = vocab SCREAMING_SNAKE_CASE_ : Dict = merges SCREAMING_SNAKE_CASE_ : Union[str, Any] = BytePairTokenizer(lowercase_ , lowercase_ , sequence_length=lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : GPTaTokenizer , *lowercase_ : Optional[Any] , **lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = [''' '''.join(lowercase_) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE_ : str = tokenizer.get_vocab() return cls(lowercase_ , lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowercase_ : Union[str, os.PathLike] , *lowercase_ : List[str] , **lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = GPTaTokenizer.from_pretrained(lowercase_ , *lowercase_ , **lowercase_) return cls.from_tokenizer(lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : List[Any]): '''simple docstring''' return cls(**lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[Any] , lowercase_ : int = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.tf_tokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.ones_like(lowercase_) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = pad_model_inputs( lowercase_ , max_seq_length=lowercase_ , pad_value=self.pad_token_id) return {"attention_mask": attention_mask, "input_ids": input_ids}
318
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 _A (__a , __a ) -> Any: """simple docstring""" if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer SCREAMING_SNAKE_CASE_ : int = flax_key_tuple[:-1] + ('''weight''',) SCREAMING_SNAKE_CASE_ : str = torch.permute(__a , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__a ): # linear layer SCREAMING_SNAKE_CASE_ : int = flax_key_tuple[:-1] + ('''weight''',) SCREAMING_SNAKE_CASE_ : List[str] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def _A (__a , __a , __a ) -> Dict: """simple docstring""" if "metadata" in layer: SCREAMING_SNAKE_CASE_ : List[Any] = layer.split('''metadata''' ) SCREAMING_SNAKE_CASE_ : Tuple = ''''''.join(split_layer[0] )[:-1] SCREAMING_SNAKE_CASE_ : List[Any] = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: SCREAMING_SNAKE_CASE_ : Optional[int] = layer.split('''kvstore''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(split_layer[0] )[:-1] SCREAMING_SNAKE_CASE_ : List[str] = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer.split('''/''' ) SCREAMING_SNAKE_CASE_ : Dict = '''/'''.join(split_layer[:-1] ) SCREAMING_SNAKE_CASE_ : List[str] = (split_layer[-1],) if "kvstore/path" in layer: SCREAMING_SNAKE_CASE_ : int = f'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: SCREAMING_SNAKE_CASE_ : str = '''file''' else: SCREAMING_SNAKE_CASE_ : str = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def _A (__a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = rename_keys(__a ) SCREAMING_SNAKE_CASE_ : str = {} for k, v in current_block.items(): SCREAMING_SNAKE_CASE_ : int = v SCREAMING_SNAKE_CASE_ : Tuple = new_current_block torch.save(__a , __a ) def _A (__a , __a , __a , __a , __a = WEIGHTS_NAME ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = convert_file_size_to_int(__a ) SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : List[Any] = {} SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Any = 0 os.makedirs(__a , exist_ok=__a ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: SCREAMING_SNAKE_CASE_ : List[str] = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(__a , sep='''/''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = {} for layer in checkpoint_info.keys(): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = get_key_and_tensorstore_dict( __a , __a , __a ) if curr_real_layer_name in all_layers: SCREAMING_SNAKE_CASE_ : Dict = content else: SCREAMING_SNAKE_CASE_ : Tuple = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file SCREAMING_SNAKE_CASE_ : Union[str, Any] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor(__a ) SCREAMING_SNAKE_CASE_ : Dict = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = rename_base_flax_keys(tuple(key.split('''/''' ) ) , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = '''/'''.join(__a ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: SCREAMING_SNAKE_CASE_ : Dict = os.path.join( __a , weights_name.replace('''.bin''' , f'-{len(__a )+1:05d}-of-???.bin' ) ) rename_and_save_block(__a , __a ) sharded_state_dicts.append(current_block.keys() ) del current_block SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = raw_weights.to(getattr(__a , __a ) ) current_block_size += weight_size total_size += weight_size # Add the last block SCREAMING_SNAKE_CASE_ : str = os.path.join(__a , weights_name.replace('''.bin''' , f'-{len(__a )+1:05d}-of-???.bin' ) ) rename_and_save_block(__a , __a ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__a ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index SCREAMING_SNAKE_CASE_ : Tuple = {} SCREAMING_SNAKE_CASE_ : Tuple = {} for idx, shard in enumerate(__a ): SCREAMING_SNAKE_CASE_ : str = weights_name.replace( '''.bin''' , f'-{idx+1:05d}-of-{len(__a ):05d}.bin' ) # len(sharded_state_dicts):05d} SCREAMING_SNAKE_CASE_ : int = os.path.join(__a , weights_name.replace('''.bin''' , f'-{idx+1:05d}-of-???.bin' ) ) os.rename(__a , os.path.join(__a , __a ) ) SCREAMING_SNAKE_CASE_ : str = shard for key in shard: SCREAMING_SNAKE_CASE_ : Optional[Any] = shard_file # Add the metadata SCREAMING_SNAKE_CASE_ : Tuple = {'''total_size''': total_size} SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(__a , __a ) , '''w''' , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = json.dumps(__a , indent=2 , sort_keys=__a ) + '''\n''' f.write(__a ) return metadata, index if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = 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.""", ) UpperCAmelCase_ : List[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 _A () -> Dict: """simple docstring""" from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer SCREAMING_SNAKE_CASE_ : Tuple = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) SCREAMING_SNAKE_CASE_ : List[str] = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) SCREAMING_SNAKE_CASE_ : Optional[int] = TaTokenizer.from_pretrained('''t5-small''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' SCREAMING_SNAKE_CASE_ : Tuple = tokenizer(__a , return_tensors='''pt''' ).input_ids SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.generate(__a , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
318
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) SCREAMING_SNAKE_CASE_ : Dict = { '''do_resize''': True, '''size''': {'''height''': 224, '''width''': 224}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], '''do_convert_rgb''': True, } SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , lowercase_) with open(self.image_processor_file , '''w''' , encoding='''utf-8''') as fp: json.dump(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , **lowercase_ : str): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , **lowercase_ : List[Any]): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , **lowercase_ : str): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] SCREAMING_SNAKE_CASE_ : Dict = [Image.fromarray(np.moveaxis(lowercase_ , 0 , -1)) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_slow.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : Any = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_fast.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , lowercase_) self.assertIsInstance(processor_fast.tokenizer , lowercase_) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , lowercase_) self.assertIsInstance(processor_fast.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_image_processor(do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=lowercase_) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , lowercase_) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Any = image_processor(lowercase_ , return_tensors='''np''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor(images=lowercase_ , return_tensors='''np''') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : str = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Optional[Any] = processor(text=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer(lowercase_) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : int = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']) # test if it raises when no input is passed with pytest.raises(lowercase_): processor() def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_ : Optional[int] = processor.batch_decode(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.batch_decode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Dict = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Dict = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Dict = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
318
1
"""simple docstring""" import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: UpperCAmelCase_ : Tuple = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[int] , lowercase_ : Optional[int] , lowercase_ : int=7 , lowercase_ : str=3 , lowercase_ : str=18 , lowercase_ : Dict=30 , lowercase_ : int=400 , lowercase_ : Any=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=True , lowercase_ : Any=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = size if size is not None else {'''height''': 20, '''width''': 20} SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : int = batch_size SCREAMING_SNAKE_CASE_ : str = num_channels SCREAMING_SNAKE_CASE_ : Optional[int] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = min_resolution SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_resolution SCREAMING_SNAKE_CASE_ : Dict = size SCREAMING_SNAKE_CASE_ : Any = do_normalize SCREAMING_SNAKE_CASE_ : str = do_convert_rgb SCREAMING_SNAKE_CASE_ : Any = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE_ : Dict = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' SCREAMING_SNAKE_CASE_ : Any = Image.open(requests.get(lowercase_ , stream=lowercase_).raw).convert('''RGB''') return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." , ) @require_torch @require_vision class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = PixaStructImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = PixaStructImageProcessingTester(self) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(lowercase_ , '''do_normalize''')) self.assertTrue(hasattr(lowercase_ , '''do_convert_rgb''')) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class(**self.image_processor_dict) SCREAMING_SNAKE_CASE_ : Any = 2048 SCREAMING_SNAKE_CASE_ : Dict = image_processor(lowercase_ , return_tensors='''pt''' , max_patches=lowercase_) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06) , atol=1e-3 , rtol=1e-3)) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE_ : Tuple = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE_ : List[Any] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor( lowercase_ , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE_ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE_ : List[str] = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : Tuple = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches SCREAMING_SNAKE_CASE_ : List[Any] = '''Hello''' SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=lowercase_ , header_text=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processor( lowercase_ , return_tensors='''pt''' , max_patches=lowercase_ , header_text=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , numpify=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , np.ndarray) SCREAMING_SNAKE_CASE_ : Optional[int] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE_ : Tuple = image_processor( lowercase_ , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , torchify=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , torch.Tensor) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE_ : Tuple = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE_ : Tuple = image_processor( lowercase_ , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." , ) @require_torch @require_vision class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = PixaStructImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = PixaStructImageProcessingTester(self , num_channels=4) SCREAMING_SNAKE_CASE_ : List[str] = 3 @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(lowercase_ , '''do_normalize''')) self.assertTrue(hasattr(lowercase_ , '''do_convert_rgb''')) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_) for image in image_inputs: self.assertIsInstance(lowercase_ , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE_ : Dict = image_processor( lowercase_ , return_tensors='''pt''' , max_patches=lowercase_).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
318
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "rwkv" __UpperCamelCase = {"max_position_embeddings": "context_length"} def __init__( self : Union[str, Any] , lowercase_ : Any=50277 , lowercase_ : str=1024 , lowercase_ : List[str]=4096 , lowercase_ : Optional[Any]=32 , lowercase_ : Any=None , lowercase_ : Any=None , lowercase_ : List[Any]=1e-5 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=0 , lowercase_ : int=6 , lowercase_ : Tuple=False , lowercase_ : Any=True , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Any = context_length SCREAMING_SNAKE_CASE_ : int = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size SCREAMING_SNAKE_CASE_ : int = intermediate_size if intermediate_size is not None else 4 * hidden_size SCREAMING_SNAKE_CASE_ : int = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : Optional[int] = rescale_every SCREAMING_SNAKE_CASE_ : Dict = use_cache SCREAMING_SNAKE_CASE_ : Dict = bos_token_id SCREAMING_SNAKE_CASE_ : Any = eos_token_id super().__init__( tie_word_embeddings=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_)
318
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) SCREAMING_SNAKE_CASE_ : Dict = { '''do_resize''': True, '''size''': {'''height''': 224, '''width''': 224}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], '''do_convert_rgb''': True, } SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , lowercase_) with open(self.image_processor_file , '''w''' , encoding='''utf-8''') as fp: json.dump(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , **lowercase_ : str): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , **lowercase_ : List[Any]): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , **lowercase_ : str): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] SCREAMING_SNAKE_CASE_ : Dict = [Image.fromarray(np.moveaxis(lowercase_ , 0 , -1)) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_slow.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : Any = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_fast.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , lowercase_) self.assertIsInstance(processor_fast.tokenizer , lowercase_) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , lowercase_) self.assertIsInstance(processor_fast.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_image_processor(do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=lowercase_) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , lowercase_) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Any = image_processor(lowercase_ , return_tensors='''np''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor(images=lowercase_ , return_tensors='''np''') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : str = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Optional[Any] = processor(text=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer(lowercase_) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : int = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']) # test if it raises when no input is passed with pytest.raises(lowercase_): processor() def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_ : Optional[int] = processor.batch_decode(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.batch_decode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Dict = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Dict = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Dict = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
318
"""simple docstring""" UpperCAmelCase_ : Optional[int] = 8.3_1_4_4_5_9_8 def _A (__a , __a ) -> float: """simple docstring""" if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example UpperCAmelCase_ : str = 300 UpperCAmelCase_ : str = 28 UpperCAmelCase_ : Any = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
318
1
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time UpperCAmelCase_ : Any = Lock() def _A (__a , __a , __a , __a , __a , __a , __a ) -> Optional[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(__a ) process_lock.release() # receive your right neighbor's value process_lock.acquire() SCREAMING_SNAKE_CASE_ : int = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left SCREAMING_SNAKE_CASE_ : int = min(__a , __a ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(__a ) process_lock.release() # receive your left neighbor's value process_lock.acquire() SCREAMING_SNAKE_CASE_ : str = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right SCREAMING_SNAKE_CASE_ : Optional[Any] = max(__a , __a ) # after all swaps are performed, send the values back to main result_pipe[1].send(__a ) def _A (__a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : str = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop SCREAMING_SNAKE_CASE_ : Tuple = Pipe() SCREAMING_SNAKE_CASE_ : str = Pipe() process_array_.append( Process( target=__a , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) SCREAMING_SNAKE_CASE_ : Any = temp_rs SCREAMING_SNAKE_CASE_ : Optional[Any] = temp_rr for i in range(1 , len(__a ) - 1 ): SCREAMING_SNAKE_CASE_ : Optional[int] = Pipe() SCREAMING_SNAKE_CASE_ : Optional[int] = Pipe() process_array_.append( Process( target=__a , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) SCREAMING_SNAKE_CASE_ : Tuple = temp_rs SCREAMING_SNAKE_CASE_ : str = temp_rr process_array_.append( Process( target=__a , args=( len(__a ) - 1, arr[len(__a ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(__a ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(__a ) ): SCREAMING_SNAKE_CASE_ : Tuple = result_pipe[p][0].recv() process_array_[p].join() return arr def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = list(range(10 , 0 , -1 ) ) print('''Initial List''' ) print(*__a ) SCREAMING_SNAKE_CASE_ : Any = odd_even_transposition(__a ) print('''Sorted List\n''' ) print(*__a ) if __name__ == "__main__": main()
318
"""simple docstring""" import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList UpperCAmelCase_ : Union[str, Any] = ["""\nclass""", """\ndef""", """\n#""", """\n@""", """\nprint""", """\nif"""] class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : int=None , lowercase_ : Dict=1): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = dataset SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase_) if n_tasks is None else n_tasks SCREAMING_SNAKE_CASE_ : Optional[int] = n_copies def __iter__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for task in range(self.n_tasks): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip()) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowercase_ , padding=lowercase_ , return_tensors='''pt''') for task in range(self.n_tasks): for _ in range(self.n_copies): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = start_length SCREAMING_SNAKE_CASE_ : List[Any] = eof_strings SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer def __call__( self : Optional[int] , lowercase_ : Any , lowercase_ : int , **lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.tokenizer.batch_decode(input_ids[:, self.start_length :]) SCREAMING_SNAKE_CASE_ : Tuple = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings)) return all(lowercase_) def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.split('''(%s)''' % '''|'''.join(__a ) , __a ) # last string should be "" return "".join(string_list[:-2] ) def _A (__a , __a , __a , __a , __a , __a=20 , **__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = defaultdict(__a ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__a ) ): with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] = batch['''ids'''].shape[-1] SCREAMING_SNAKE_CASE_ : Tuple = accelerator.unwrap_model(__a ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']] , num_return_sequences=__a , **__a ) # each task is generated batch_size times SCREAMING_SNAKE_CASE_ : List[Any] = batch['''task_id'''].repeat(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.pad_across_processes( __a , dim=1 , pad_index=tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) SCREAMING_SNAKE_CASE_ : int = generated_tokens.cpu().numpy() SCREAMING_SNAKE_CASE_ : Optional[Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__a , __a ): gen_token_dict[task].append(__a ) SCREAMING_SNAKE_CASE_ : int = [[] for _ in range(__a )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) code_gens[task].append(remove_last_block(__a ) ) return code_gens def _A () -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = HfArgumentParser(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric SCREAMING_SNAKE_CASE_ : Any = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing SCREAMING_SNAKE_CASE_ : str = '''false''' if args.num_workers is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() set_seed(args.seed , device_specific=__a ) # Load model and tokenizer SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.eos_token SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings SCREAMING_SNAKE_CASE_ : List[str] = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0 , __a , __a )] ), } # Load evaluation dataset and metric SCREAMING_SNAKE_CASE_ : Optional[int] = load_dataset('''openai_humaneval''' ) SCREAMING_SNAKE_CASE_ : str = load_metric('''code_eval''' ) SCREAMING_SNAKE_CASE_ : int = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) SCREAMING_SNAKE_CASE_ : List[str] = args.n_samples // args.batch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = TokenizedDataset(__a , human_eval['''test'''] , n_copies=__a , n_tasks=__a ) # do not confuse args.batch_size, which is actually the num_return_sequences SCREAMING_SNAKE_CASE_ : Optional[int] = DataLoader(__a , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: SCREAMING_SNAKE_CASE_ : Any = code_eval_metric.compute(references=[''''''] , predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = accelerator.prepare(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = complete_code( __a , __a , __a , __a , n_tasks=__a , batch_size=args.batch_size , **__a , ) if accelerator.is_main_process: SCREAMING_SNAKE_CASE_ : int = [] for task in tqdm(range(__a ) ): SCREAMING_SNAKE_CASE_ : Tuple = human_eval['''test'''][task]['''test'''] SCREAMING_SNAKE_CASE_ : Tuple = f'check({human_eval["test"][task]["entry_point"]})' references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = code_eval_metric.compute( references=__a , predictions=__a , num_workers=args.num_workers ) print(f'Results: {pass_at_k}' ) # Save results to json file with open(args.output_file , '''w''' ) as fp: json.dump(__a , __a ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
318
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ : Tuple = { """configuration_cpmant""": ["""CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CpmAntConfig"""], """tokenization_cpmant""": ["""CpmAntTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ """CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST""", """CpmAntForCausalLM""", """CpmAntModel""", """CpmAntPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "feature_extractor"] __UpperCamelCase = "TvltImageProcessor" __UpperCamelCase = "TvltFeatureExtractor" def __init__( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(image_processor=lowercase_ , feature_extractor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = feature_extractor def __call__( self : Any , lowercase_ : str=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : str=None , lowercase_ : int=False , lowercase_ : Union[str, Any]=False , *lowercase_ : List[Any] , **lowercase_ : List[str] , ): '''simple docstring''' if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''') SCREAMING_SNAKE_CASE_ : Any = None if images is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor(lowercase_ , mask_pixel=lowercase_ , *lowercase_ , **lowercase_) if images_mixed is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , is_mixed=lowercase_ , *lowercase_ , **lowercase_) if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor( lowercase_ , *lowercase_ , sampling_rate=lowercase_ , mask_audio=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {} if audio is not None: output_dict.update(lowercase_) if images is not None: output_dict.update(lowercase_) if images_mixed_dict is not None: output_dict.update(lowercase_) return output_dict @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
318
1
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = {"""vocab_file""": """spiece.model"""} UpperCAmelCase_ : Tuple = { """vocab_file""": { """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""", } } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[str]=False , lowercase_ : int=True , lowercase_ : Union[str, Any]=False , lowercase_ : int="<s>" , lowercase_ : int="</s>" , lowercase_ : Optional[int]="<unk>" , lowercase_ : Any="<sep>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Tuple="<cls>" , lowercase_ : List[str]="<mask>" , lowercase_ : Optional[Any]=["<eop>", "<eod>"] , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else mask_token SCREAMING_SNAKE_CASE_ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=lowercase_ , remove_space=lowercase_ , keep_accents=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , pad_token=lowercase_ , cls_token=lowercase_ , mask_token=lowercase_ , additional_special_tokens=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE_ : Any = do_lower_case SCREAMING_SNAKE_CASE_ : List[str] = remove_space SCREAMING_SNAKE_CASE_ : Any = keep_accents SCREAMING_SNAKE_CASE_ : str = vocab_file SCREAMING_SNAKE_CASE_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(lowercase_) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''') SCREAMING_SNAKE_CASE_ : List[Any] = jieba SCREAMING_SNAKE_CASE_ : List[Any] = str.maketrans(''' \n''' , '''\u2582\u2583''') @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return len(self.sp_model) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Any = None return state def __setstate__( self : List[str] , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : int): '''simple docstring''' if self.remove_space: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ''' '''.join(inputs.strip().split()) else: SCREAMING_SNAKE_CASE_ : str = inputs SCREAMING_SNAKE_CASE_ : Tuple = outputs.replace('''``''' , '''"''').replace('''\'\'''' , '''"''') if not self.keep_accents: SCREAMING_SNAKE_CASE_ : int = unicodedata.normalize('''NFKD''' , lowercase_) SCREAMING_SNAKE_CASE_ : str = ''''''.join([c for c in outputs if not unicodedata.combining(lowercase_)]) if self.do_lower_case: SCREAMING_SNAKE_CASE_ : str = outputs.lower() return outputs def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.preprocess_text(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.encode(lowercase_ , out_type=lowercase_) SCREAMING_SNAKE_CASE_ : int = [] for piece in pieces: if len(lowercase_) > 1 and piece[-1] == str(''',''') and piece[-2].isdigit(): SCREAMING_SNAKE_CASE_ : List[Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(lowercase_ , '''''')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: SCREAMING_SNAKE_CASE_ : Dict = cur_pieces[1:] else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(lowercase_) else: new_pieces.append(lowercase_) return new_pieces def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str]): '''simple docstring''' return self.sp_model.PieceToId(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Any): '''simple docstring''' return self.sp_model.IdToPiece(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : Tuple = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is not None: return ([0] * len(lowercase_)) + [1] + ([0] * len(lowercase_)) + [1, 1] return ([0] * len(lowercase_)) + [1, 1] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : str = [2] if token_ids_a is None: return len(token_ids_a + sep) * [0] + cls_segment_id return len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] + cls_segment_id def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : int = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : Tuple = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = super()._decode(*lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = text.replace(''' ''' , '''''').replace('''\u2582''' , ''' ''').replace('''\u2583''' , '''\n''') return text
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "SpeechT5FeatureExtractor" __UpperCamelCase = "SpeechT5Tokenizer" def __init__( self : Any , lowercase_ : Dict , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(lowercase_ , lowercase_) def __call__( self : List[Any] , *lowercase_ : List[Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''audio''' , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.pop('''text''' , lowercase_) SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('''text_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''audio_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''sampling_rate''' , lowercase_) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''') if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''') if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''') if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor(lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) elif text is not None: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = None if audio_target is not None: SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extractor(audio_target=lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = targets['''input_values'''] elif text_target is not None: SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : int = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = labels SCREAMING_SNAKE_CASE_ : Optional[Any] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Any = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : Tuple , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''input_values''' , lowercase_) SCREAMING_SNAKE_CASE_ : int = kwargs.pop('''input_ids''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''labels''' , lowercase_) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''') if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''') if input_values is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) elif input_ids is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.pad(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : List[Any] = None if labels is not None: if "input_ids" in labels or (isinstance(lowercase_ , lowercase_) and "input_ids" in labels[0]): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer.pad(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Dict = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.feature_size SCREAMING_SNAKE_CASE_ : Optional[int] = self.feature_extractor.num_mel_bins SCREAMING_SNAKE_CASE_ : str = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : str = feature_size_hack SCREAMING_SNAKE_CASE_ : Dict = targets['''input_values'''] else: SCREAMING_SNAKE_CASE_ : List[Any] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Dict = labels SCREAMING_SNAKE_CASE_ : List[str] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowercase_ : Optional[int] , **lowercase_ : Tuple): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *lowercase_ : Dict , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_)
318
1
"""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 ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=lowercase_).to(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained('''google/mt5-small''') SCREAMING_SNAKE_CASE_ : Dict = tokenizer('''Hello there''' , return_tensors='''pt''').input_ids SCREAMING_SNAKE_CASE_ : int = tokenizer('''Hi I am''' , return_tensors='''pt''').input_ids SCREAMING_SNAKE_CASE_ : Dict = model(input_ids.to(lowercase_) , labels=labels.to(lowercase_)).loss SCREAMING_SNAKE_CASE_ : str = -(labels.shape[-1] * loss.item()) SCREAMING_SNAKE_CASE_ : str = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
318
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.inf def set_batch_size(__a ) -> None: nonlocal batch_size if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__a , __a ) and feature.dtype == "binary": SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__a , __a ) return None if batch_size is np.inf else batch_size class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , lowercase_ : NestedDataStructureLike[PathLike] , lowercase_ : Optional[NamedSplit] = None , lowercase_ : Optional[Features] = None , lowercase_ : str = None , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : Optional[int] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , split=lowercase_ , features=lowercase_ , cache_dir=lowercase_ , keep_in_memory=lowercase_ , streaming=lowercase_ , num_proc=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = path_or_paths if isinstance(lowercase_ , lowercase_) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_ : Any = _PACKAGED_DATASETS_MODULES['''parquet'''][1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = Parquet( cache_dir=lowercase_ , data_files=lowercase_ , features=lowercase_ , hash=lowercase_ , **lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE_ : str = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None self.builder.download_and_prepare( download_config=lowercase_ , download_mode=lowercase_ , verification_mode=lowercase_ , base_path=lowercase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_ : Any = self.builder.as_dataset( split=self.split , verification_mode=lowercase_ , in_memory=self.keep_in_memory) return dataset class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Dataset , lowercase_ : Union[PathLike, BinaryIO] , lowercase_ : Optional[int] = None , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = dataset SCREAMING_SNAKE_CASE_ : Dict = path_or_buf SCREAMING_SNAKE_CASE_ : List[Any] = batch_size or get_writer_batch_size(dataset.features) SCREAMING_SNAKE_CASE_ : Any = parquet_writer_kwargs def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , '''wb+''') as buffer: SCREAMING_SNAKE_CASE_ : Optional[Any] = self._write(file_obj=lowercase_ , batch_size=lowercase_ , **self.parquet_writer_kwargs) else: SCREAMING_SNAKE_CASE_ : str = self._write(file_obj=self.path_or_buf , batch_size=lowercase_ , **self.parquet_writer_kwargs) return written def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : BinaryIO , lowercase_ : int , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = parquet_writer_kwargs.pop('''path_or_buf''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dataset.features.arrow_schema SCREAMING_SNAKE_CASE_ : Tuple = pq.ParquetWriter(lowercase_ , schema=lowercase_ , **lowercase_) for offset in logging.tqdm( range(0 , len(self.dataset) , lowercase_) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): SCREAMING_SNAKE_CASE_ : List[Any] = query_table( table=self.dataset._data , key=slice(lowercase_ , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(lowercase_) written += batch.nbytes writer.close() return written
318
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__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = DDIMPipeline __UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __UpperCamelCase = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } __UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = DDIMScheduler() SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'''unet''': unet, '''scheduler''': scheduler} return components def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Union[str, Any] , lowercase_ : Tuple=0): '''simple docstring''' if str(lowercase_).startswith('''mps'''): SCREAMING_SNAKE_CASE_ : int = torch.manual_seed(lowercase_) else: SCREAMING_SNAKE_CASE_ : int = torch.Generator(device=lowercase_).manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = '''cpu''' SCREAMING_SNAKE_CASE_ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : Dict = self.pipeline_class(**lowercase_) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_dummy_inputs(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Optional[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3)) SCREAMING_SNAKE_CASE_ : List[str] = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04]) SCREAMING_SNAKE_CASE_ : Dict = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(lowercase_ , 1e-3) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' super().test_save_load_local(expected_max_difference=3e-3) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=3e-3) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE_ : List[Any] = UNetaDModel.from_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = DDIMScheduler() SCREAMING_SNAKE_CASE_ : Any = DDIMPipeline(unet=lowercase_ , scheduler=lowercase_) ddim.to(lowercase_) ddim.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : int = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : str = ddim(generator=lowercase_ , eta=0.0 , output_type='''numpy''').images SCREAMING_SNAKE_CASE_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_ : Dict = np.array([0.17_23, 0.16_17, 0.16_00, 0.16_26, 0.14_97, 0.15_13, 0.15_05, 0.14_42, 0.14_53]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = '''google/ddpm-ema-bedroom-256''' SCREAMING_SNAKE_CASE_ : Optional[int] = UNetaDModel.from_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = DDIMScheduler.from_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : int = DDIMPipeline(unet=lowercase_ , scheduler=lowercase_) ddpm.to(lowercase_) ddpm.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = ddpm(generator=lowercase_ , output_type='''numpy''').images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array([0.00_60, 0.02_01, 0.03_44, 0.00_24, 0.00_18, 0.00_02, 0.00_22, 0.00_00, 0.00_69]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
318
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = ["""model.decoder.embed_positions.weights"""] def _A (__a ) -> Dict: """simple docstring""" if "emb" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def _A (__a , __a ) -> Tuple[Dict, Dict]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(state_dict.keys() ) SCREAMING_SNAKE_CASE_ : int = {} for key in keys: SCREAMING_SNAKE_CASE_ : int = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ : int = rename_keys(__a ) if "in_proj_weight" in key: # split fused qkv proj SCREAMING_SNAKE_CASE_ : List[str] = val[:hidden_size, :] SCREAMING_SNAKE_CASE_ : List[str] = val[hidden_size : 2 * hidden_size, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: SCREAMING_SNAKE_CASE_ : int = val else: SCREAMING_SNAKE_CASE_ : Any = val return state_dict, enc_dec_proj_state_dict def _A (__a ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values SCREAMING_SNAKE_CASE_ : Optional[int] = 10_24 SCREAMING_SNAKE_CASE_ : Tuple = 24 SCREAMING_SNAKE_CASE_ : Optional[Any] = 16 elif checkpoint == "medium": SCREAMING_SNAKE_CASE_ : List[str] = 15_36 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : Optional[int] = 24 elif checkpoint == "large": SCREAMING_SNAKE_CASE_ : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : int = 32 else: raise ValueError(f'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' ) SCREAMING_SNAKE_CASE_ : List[Any] = MusicgenDecoderConfig( hidden_size=__a , ffn_dim=hidden_size * 4 , num_hidden_layers=__a , num_attention_heads=__a , ) return config @torch.no_grad() def _A (__a , __a=None , __a=None , __a="cpu" ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = MusicGen.get_pretrained(__a , device=__a ) SCREAMING_SNAKE_CASE_ : Dict = decoder_config_from_checkpoint(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = fairseq_model.lm.state_dict() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = rename_state_dict( __a , hidden_size=decoder_config.hidden_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = TaEncoderModel.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : List[str] = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) SCREAMING_SNAKE_CASE_ : int = MusicgenForCausalLM(__a ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = decoder.load_state_dict(__a , strict=__a ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__a ) if len(__a ) > 0: raise ValueError(f'Missing key(s) in state_dict: {missing_keys}' ) if len(__a ) > 0: raise ValueError(f'Unexpected key(s) in state_dict: {unexpected_keys}' ) # init the composite model SCREAMING_SNAKE_CASE_ : str = MusicgenForConditionalGeneration(text_encoder=__a , audio_encoder=__a , decoder=__a ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__a ) # check we can do a forward pass SCREAMING_SNAKE_CASE_ : Dict = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=__a , decoder_input_ids=__a ).logits if logits.shape != (8, 1, 20_48): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : str = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) SCREAMING_SNAKE_CASE_ : Tuple = MusicgenProcessor(feature_extractor=__a , tokenizer=__a ) # set the appropriate bos/pad token ids SCREAMING_SNAKE_CASE_ : str = 20_48 SCREAMING_SNAKE_CASE_ : List[Any] = 20_48 # set other default generation config params SCREAMING_SNAKE_CASE_ : int = int(30 * audio_encoder.config.frame_rate ) SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Optional[Any] = 3.0 if pytorch_dump_folder is not None: Path(__a ).mkdir(exist_ok=__a ) logger.info(f'Saving model {checkpoint} to {pytorch_dump_folder}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if repo_id: logger.info(f'Pushing model {checkpoint} to {repo_id}' ) model.push_to_hub(__a ) processor.push_to_hub(__a ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) UpperCAmelCase_ : Dict = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
318
1
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = BioGptTokenizer __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ : str = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] SCREAMING_SNAKE_CASE_ : Optional[int] = dict(zip(lowercase_ , range(len(lowercase_)))) SCREAMING_SNAKE_CASE_ : str = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file''']) with open(self.vocab_file , '''w''') as fp: fp.write(json.dumps(lowercase_)) with open(self.merges_file , '''w''') as fp: fp.write('''\n'''.join(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = '''lower newer''' SCREAMING_SNAKE_CASE_ : str = '''lower newer''' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = BioGptTokenizer(self.vocab_file , self.merges_file) SCREAMING_SNAKE_CASE_ : int = '''lower''' SCREAMING_SNAKE_CASE_ : List[str] = ['''low''', '''er</w>'''] SCREAMING_SNAKE_CASE_ : Dict = tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Any = tokens + ['''<unk>'''] SCREAMING_SNAKE_CASE_ : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_) , lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''') SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.encode('''sequence builders''' , add_special_tokens=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.build_inputs_with_special_tokens(lowercase_) SCREAMING_SNAKE_CASE_ : int = tokenizer.build_inputs_with_special_tokens(lowercase_ , lowercase_) self.assertTrue(encoded_sentence == [2] + text) self.assertTrue(encoded_pair == [2] + text + [2] + text_a)
318
"""simple docstring""" from pathlib import Path import numpy as np from PIL import Image def _A (__a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def _A (__a ) -> np.ndarray: """simple docstring""" return (gray > 1_27) & (gray <= 2_55) def _A (__a , __a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = np.zeros_like(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE_ : Union[str, Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE_ : Optional[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE_ : Any = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCAmelCase_ : Dict = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" UpperCAmelCase_ : List[Any] = np.array(Image.open(lena_path)) # kernel to be applied UpperCAmelCase_ : Any = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCAmelCase_ : Tuple = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCAmelCase_ : List[str] = Image.fromarray(output).convert("""RGB""") pil_img.save("""result_dilation.png""")
318
1
"""simple docstring""" UpperCAmelCase_ : Tuple = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def _A () -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = input('''Enter message: ''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = input('''Enter key [alphanumeric]: ''' ) SCREAMING_SNAKE_CASE_ : int = input('''Encrypt/Decrypt [e/d]: ''' ) if mode.lower().startswith('''e''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = '''encrypt''' SCREAMING_SNAKE_CASE_ : List[str] = encrypt_message(__a , __a ) elif mode.lower().startswith('''d''' ): SCREAMING_SNAKE_CASE_ : Tuple = '''decrypt''' SCREAMING_SNAKE_CASE_ : Dict = decrypt_message(__a , __a ) print(f'\n{mode.title()}ed message:' ) print(__a ) def _A (__a , __a ) -> str: """simple docstring""" return translate_message(__a , __a , '''encrypt''' ) def _A (__a , __a ) -> str: """simple docstring""" return translate_message(__a , __a , '''decrypt''' ) def _A (__a , __a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : Dict = key.upper() for symbol in message: SCREAMING_SNAKE_CASE_ : Union[str, Any] = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__a ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__a ): SCREAMING_SNAKE_CASE_ : int = 0 else: translated.append(__a ) return "".join(__a ) if __name__ == "__main__": main()
318
"""simple docstring""" from collections import defaultdict def _A (__a , __a ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = first_str.lower().strip() SCREAMING_SNAKE_CASE_ : List[Any] = second_str.lower().strip() # Remove whitespace SCREAMING_SNAKE_CASE_ : Dict = first_str.replace(''' ''' , '''''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = second_str.replace(''' ''' , '''''' ) # Strings of different lengths are not anagrams if len(__a ) != len(__a ): return False # Default values for count should be 0 SCREAMING_SNAKE_CASE_ : defaultdict[str, int] = defaultdict(__a ) # For each character in input strings, # increment count in the corresponding for i in range(len(__a ) ): 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() UpperCAmelCase_ : Any = input("""Enter the first string """).strip() UpperCAmelCase_ : Optional[int] = input("""Enter the second string """).strip() UpperCAmelCase_ : Union[str, Any] = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {'' if status else 'not '}anagrams.''')
318
1
"""simple docstring""" import colorsys from PIL import Image # type: ignore def _A (__a , __a , __a ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = x SCREAMING_SNAKE_CASE_ : List[Any] = y for step in range(__a ): # noqa: B007 SCREAMING_SNAKE_CASE_ : int = a * a - b * b + x SCREAMING_SNAKE_CASE_ : Any = 2 * a * b + y SCREAMING_SNAKE_CASE_ : str = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _A (__a ) -> tuple: """simple docstring""" if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _A (__a ) -> tuple: """simple docstring""" if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(__a , 1 , 1 ) ) def _A (__a = 8_00 , __a = 6_00 , __a = -0.6 , __a = 0 , __a = 3.2 , __a = 50 , __a = True , ) -> Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Image.new('''RGB''' , (image_width, image_height) ) SCREAMING_SNAKE_CASE_ : Dict = img.load() # loop through the image-coordinates for image_x in range(__a ): for image_y in range(__a ): # determine the figure-coordinates based on the image-coordinates SCREAMING_SNAKE_CASE_ : Union[str, Any] = figure_width / image_width * image_height SCREAMING_SNAKE_CASE_ : Optional[Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width SCREAMING_SNAKE_CASE_ : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height SCREAMING_SNAKE_CASE_ : int = get_distance(__a , __a , __a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: SCREAMING_SNAKE_CASE_ : Dict = get_color_coded_rgb(__a ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = get_black_and_white_rgb(__a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase_ : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
318
"""simple docstring""" import argparse from collections import defaultdict import yaml UpperCAmelCase_ : Optional[Any] = """docs/source/en/_toctree.yml""" def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 SCREAMING_SNAKE_CASE_ : List[Any] = [key for key, value in counts.items() if value > 1] SCREAMING_SNAKE_CASE_ : int = [] for duplicate_key in duplicates: SCREAMING_SNAKE_CASE_ : List[str] = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(__a , key=lambda __a : s["title"].lower() ) def _A (__a=False ) -> Tuple: """simple docstring""" with open(__a , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE_ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE_ : str = content[api_idx]['''sections'''] # Then to the model doc SCREAMING_SNAKE_CASE_ : List[Any] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = api_doc[model_idx]['''sections'''] SCREAMING_SNAKE_CASE_ : str = [(idx, section) for idx, section in enumerate(__a ) if '''sections''' in section] SCREAMING_SNAKE_CASE_ : Optional[Any] = False for idx, modality_doc in modalities_docs: SCREAMING_SNAKE_CASE_ : List[str] = modality_doc['''sections'''] SCREAMING_SNAKE_CASE_ : Union[str, Any] = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: SCREAMING_SNAKE_CASE_ : str = True if overwrite: SCREAMING_SNAKE_CASE_ : Optional[int] = new_modality_doc if diff: if overwrite: SCREAMING_SNAKE_CASE_ : List[Any] = model_doc SCREAMING_SNAKE_CASE_ : int = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) 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__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Tuple = parser.parse_args() check_model_doc(args.fix_and_overwrite)
318
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE_ : Tuple = (32, 32) SCREAMING_SNAKE_CASE_ : Union[str, Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0)).to(lowercase_) return image @property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) return model @property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Dict = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' def extract(*lowercase_ : List[Any] , **lowercase_ : List[Any]): class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = torch.ones([0]) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Any): '''simple docstring''' self.pixel_values.to(lowercase_) return self return Out() return extract def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_cond_unet SCREAMING_SNAKE_CASE_ : int = PNDMScheduler(skip_prk_steps=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_vae SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_text_encoder SCREAMING_SNAKE_CASE_ : Union[str, Any] = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''') SCREAMING_SNAKE_CASE_ : List[Any] = 77 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_image.to(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE_ : Dict = AltDiffusionImgaImgPipeline( unet=lowercase_ , scheduler=lowercase_ , vae=lowercase_ , text_encoder=lowercase_ , tokenizer=lowercase_ , safety_checker=lowercase_ , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE_ : Dict = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = alt_pipe.to(lowercase_) alt_pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : str = '''A painting of a squirrel eating a burger''' SCREAMING_SNAKE_CASE_ : Dict = torch.Generator(device=lowercase_).manual_seed(0) SCREAMING_SNAKE_CASE_ : int = alt_pipe( [prompt] , generator=lowercase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=lowercase_ , ) SCREAMING_SNAKE_CASE_ : int = output.images SCREAMING_SNAKE_CASE_ : Tuple = torch.Generator(device=lowercase_).manual_seed(0) SCREAMING_SNAKE_CASE_ : Optional[Any] = alt_pipe( [prompt] , generator=lowercase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=lowercase_ , return_dict=lowercase_ , )[0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE_ : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 5e-3 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''') def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_cond_unet SCREAMING_SNAKE_CASE_ : Optional[int] = PNDMScheduler(skip_prk_steps=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_vae SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_text_encoder SCREAMING_SNAKE_CASE_ : Union[str, Any] = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''') SCREAMING_SNAKE_CASE_ : List[Any] = 77 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.dummy_image.to(lowercase_) # put models in fp16 SCREAMING_SNAKE_CASE_ : str = unet.half() SCREAMING_SNAKE_CASE_ : Any = vae.half() SCREAMING_SNAKE_CASE_ : Dict = bert.half() # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE_ : str = AltDiffusionImgaImgPipeline( unet=lowercase_ , scheduler=lowercase_ , vae=lowercase_ , text_encoder=lowercase_ , tokenizer=lowercase_ , safety_checker=lowercase_ , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE_ : Tuple = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = alt_pipe.to(lowercase_) alt_pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = '''A painting of a squirrel eating a burger''' SCREAMING_SNAKE_CASE_ : Dict = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Any = alt_pipe( [prompt] , generator=lowercase_ , num_inference_steps=2 , output_type='''np''' , image=lowercase_ , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE_ : Optional[Any] = init_image.resize((760, 504)) SCREAMING_SNAKE_CASE_ : Tuple = '''BAAI/AltDiffusion''' SCREAMING_SNAKE_CASE_ : Any = AltDiffusionImgaImgPipeline.from_pretrained( lowercase_ , safety_checker=lowercase_ , ) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_ : int = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Tuple = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Any = pipe( prompt=lowercase_ , image=lowercase_ , strength=0.75 , guidance_scale=7.5 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Tuple = output.images[0] SCREAMING_SNAKE_CASE_ : Optional[int] = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : List[str] = init_image.resize((768, 512)) SCREAMING_SNAKE_CASE_ : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''') SCREAMING_SNAKE_CASE_ : Optional[Any] = '''BAAI/AltDiffusion''' SCREAMING_SNAKE_CASE_ : Any = AltDiffusionImgaImgPipeline.from_pretrained( lowercase_ , safety_checker=lowercase_ , ) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_ : str = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=lowercase_ , image=lowercase_ , strength=0.75 , guidance_scale=7.5 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image).max() < 1e-2
318
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase_ : Optional[int] = { """configuration_encodec""": [ """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EncodecConfig""", ], """feature_extraction_encodec""": ["""EncodecFeatureExtractor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = [ """ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST""", """EncodecModel""", """EncodecPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
318
"""simple docstring""" from __future__ import annotations UpperCAmelCase_ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase_ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase_ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _A (__a , __a , __a , __a ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _A (__a ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _A (__a ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__a ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__a , __a , __a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = digit if sudoku(__a ) is not None: return grid SCREAMING_SNAKE_CASE_ : Any = 0 return None def _A (__a ) -> None: """simple docstring""" for row in grid: for cell in row: print(__a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") UpperCAmelCase_ : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
318
1
"""simple docstring""" import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = MgpstrTokenizer __UpperCamelCase = False __UpperCamelCase = {} __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' super().setUp() # fmt: off SCREAMING_SNAKE_CASE_ : List[str] = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on SCREAMING_SNAKE_CASE_ : int = dict(zip(lowercase_ , range(len(lowercase_)))) SCREAMING_SNAKE_CASE_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as fp: fp.write(json.dumps(lowercase_) + '''\n''') def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , **lowercase_ : int): '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = '''tester''' SCREAMING_SNAKE_CASE_ : Optional[Any] = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizers(do_lower_case=lowercase_) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}'): SCREAMING_SNAKE_CASE_ : int = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token}) SCREAMING_SNAKE_CASE_ : int = tokenizer.encode([special_token] , add_special_tokens=lowercase_) self.assertEqual(len(lowercase_) , 1) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.decode(lowercase_ , skip_special_tokens=lowercase_) self.assertTrue(special_token not in decoded) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}'): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self.get_input_output_texts(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.tokenize(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.convert_tokens_to_ids(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = tokenizer.convert_ids_to_tokens(lowercase_) self.assertNotEqual(len(lowercase_) , 0) SCREAMING_SNAKE_CASE_ : Any = tokenizer.decode(lowercase_) self.assertIsInstance(lowercase_ , lowercase_) self.assertEqual(text_a.replace(''' ''' , '''''') , lowercase_) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''') def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass
318
"""simple docstring""" from itertools import permutations def _A (__a ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAKE_CASE_ : List[str] = [7, 11, 13, 17] for i, test in enumerate(__a ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _A (__a = 10 ) -> int: """simple docstring""" return sum( int(''''''.join(map(__a , __a ) ) ) for num in permutations(range(__a ) ) if is_substring_divisible(__a ) ) if __name__ == "__main__": print(f'''{solution() = }''')
318
1
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _A (__a = 8 ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ascii_letters + digits + punctuation return "".join(secrets.choice(__a ) for _ in range(__a ) ) def _A (__a , __a ) -> str: """simple docstring""" i -= len(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = i // 3 SCREAMING_SNAKE_CASE_ : List[str] = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( chars_incl + random(__a , quotient + remainder ) + random(__a , __a ) + random(__a , __a ) ) SCREAMING_SNAKE_CASE_ : Any = list(__a ) shuffle(__a ) return "".join(__a ) # random is a generalised function for letters, characters and numbers def _A (__a , __a ) -> str: """simple docstring""" return "".join(secrets.choice(__a ) for _ in range(__a ) ) def _A (__a , __a ) -> List[Any]: """simple docstring""" pass # Put your code here... def _A (__a , __a ) -> Any: """simple docstring""" pass # Put your code here... def _A (__a , __a ) -> Optional[Any]: """simple docstring""" pass # Put your code here... def _A (__a , __a = 8 ) -> bool: """simple docstring""" if len(__a ) < min_length: # Your Password must be at least 8 characters long return False SCREAMING_SNAKE_CASE_ : Tuple = any(char in ascii_uppercase for char in password ) SCREAMING_SNAKE_CASE_ : Dict = any(char in ascii_lowercase for char in password ) SCREAMING_SNAKE_CASE_ : Tuple = any(char in digits for char in password ) SCREAMING_SNAKE_CASE_ : List[Any] = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _A () -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = int(input('''Please indicate the max length of your password: ''' ).strip() ) SCREAMING_SNAKE_CASE_ : List[str] = input( '''Please indicate the characters that must be in your password: ''' ).strip() print('''Password generated:''' , password_generator(__a ) ) print( '''Alternative Password generated:''' , alternative_password_generator(__a , __a ) , ) print('''[If you are thinking of using this passsword, You better save it.]''' ) if __name__ == "__main__": main()
318
"""simple docstring""" UpperCAmelCase_ : List[Any] = 9.8_0_6_6_5 def _A (__a , __a , __a = g ) -> float: """simple docstring""" if fluid_density <= 0: raise ValueError('''Impossible fluid density''' ) if volume < 0: raise ValueError('''Impossible Object volume''' ) if gravity <= 0: raise ValueError('''Impossible Gravity''' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
318
1
"""simple docstring""" UpperCAmelCase_ : Optional[int] = 8.3_1_4_4_5_9_8 def _A (__a , __a ) -> float: """simple docstring""" if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example UpperCAmelCase_ : str = 300 UpperCAmelCase_ : str = 28 UpperCAmelCase_ : Any = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
318
"""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. UpperCAmelCase_ : Union[str, Any] = abspath(join(dirname(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 _A (__a ) -> Union[str, Any]: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def _A (__a ) -> Any: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE_ : Optional[Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a , id=__a )
318
1
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Dict , lowercase_ : Optional[Any] , lowercase_ : str=3 , lowercase_ : str=32 , lowercase_ : Optional[int]=3 , lowercase_ : Optional[Any]=10 , lowercase_ : Any=[10, 20, 30, 40] , lowercase_ : List[str]=[1, 1, 2, 1] , lowercase_ : Union[str, Any]=True , lowercase_ : Any=True , lowercase_ : Dict="relu" , lowercase_ : Dict=3 , lowercase_ : Union[str, Any]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = parent SCREAMING_SNAKE_CASE_ : Dict = batch_size SCREAMING_SNAKE_CASE_ : str = image_size SCREAMING_SNAKE_CASE_ : Tuple = num_channels SCREAMING_SNAKE_CASE_ : List[str] = embeddings_size SCREAMING_SNAKE_CASE_ : str = hidden_sizes SCREAMING_SNAKE_CASE_ : Dict = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = hidden_act SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : int = scope SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_config() return config, pixel_values def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : List[Any] , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = FlaxRegNetModel(config=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase_) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : List[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxRegNetForImageClassification(config=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = FlaxRegNetModelTester(self) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) @unittest.skip(reason='''RegNet does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''RegNet does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Tuple = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = inspect.signature(model.__call__) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' def check_hidden_states_output(lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Tuple): SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.num_stages self.assertEqual(len(lowercase_) , expected_num_stages + 1) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Union[str, Any] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : int = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) @jax.jit def model_jitted(lowercase_ : Any , **lowercase_ : Optional[int]): return model(pixel_values=lowercase_ , **lowercase_) with self.subTest('''JIT Enabled'''): SCREAMING_SNAKE_CASE_ : Optional[int] = model_jitted(**lowercase_).to_tuple() with self.subTest('''JIT Disabled'''): with jax.disable_jit(): SCREAMING_SNAKE_CASE_ : Tuple = model_jitted(**lowercase_).to_tuple() self.assertEqual(len(lowercase_) , len(lowercase_)) for jitted_output, output in zip(lowercase_ , lowercase_): self.assertEqual(jitted_output.shape , output.shape) def _A () -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''') if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''') SCREAMING_SNAKE_CASE_ : List[str] = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''np''') SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Any = (1, 1000) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.array([-0.41_80, -1.50_51, -3.48_36]) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
318
"""simple docstring""" import argparse import os import re import packaging.version UpperCAmelCase_ : Any = """examples/""" UpperCAmelCase_ : Optional[int] = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCAmelCase_ : List[Any] = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCAmelCase_ : Optional[int] = """README.md""" def _A (__a , __a , __a ) -> int: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Optional[Any] = f.read() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = REPLACE_PATTERNS[pattern] SCREAMING_SNAKE_CASE_ : Optional[int] = replace.replace('''VERSION''' , __a ) SCREAMING_SNAKE_CASE_ : Tuple = re_pattern.sub(__a , __a ) with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(__a ) def _A (__a ) -> int: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a , __a ) , __a , pattern='''examples''' ) def _A (__a , __a=False ) -> List[str]: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a , __a , __a ) if not patch: update_version_in_examples(__a ) def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' SCREAMING_SNAKE_CASE_ : Optional[int] = '''1. Want to contribute a new model?''' with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Tuple = f.readlines() # Find the start of the list. SCREAMING_SNAKE_CASE_ : Tuple = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Dict = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): SCREAMING_SNAKE_CASE_ : List[Any] = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__a ) def _A () -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] , '''r''' ) as f: SCREAMING_SNAKE_CASE_ : Any = f.read() SCREAMING_SNAKE_CASE_ : Dict = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def _A (__a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: SCREAMING_SNAKE_CASE_ : List[Any] = default_version.base_version elif patch: SCREAMING_SNAKE_CASE_ : int = f'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: SCREAMING_SNAKE_CASE_ : Any = f'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are you releasing? [{default_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = default_version print(f'Updating version to {version}.' ) global_version_update(__a , patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def _A () -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_version() SCREAMING_SNAKE_CASE_ : Any = f'{current_version.major}.{current_version.minor + 1}.0.dev0' SCREAMING_SNAKE_CASE_ : Union[str, Any] = current_version.base_version # Check with the user we got that right. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are we developing now? [{dev_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[int] = dev_version print(f'Updating version to {version}.' ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCAmelCase_ : int = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
318
1
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ : str = get_tests_dir("""fixtures/test_sentencepiece_no_bos.model""") @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = PegasusTokenizer __UpperCamelCase = PegasusTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_ : Optional[Any] = PegasusTokenizer(lowercase_) tokenizer.save_pretrained(self.tmpdirname) @cached_property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''') def _SCREAMING_SNAKE_CASE ( self : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Dict): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = '''</s>''' SCREAMING_SNAKE_CASE_ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_) , lowercase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_) , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<pad>''') self.assertEqual(vocab_keys[1] , '''</s>''') self.assertEqual(vocab_keys[-1] , '''v''') self.assertEqual(len(lowercase_) , 1103) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1103) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=lowercase_ , add_special_tokens=lowercase_).input_ids[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=lowercase_ , add_special_tokens=lowercase_).input_ids[0] self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE_ : int = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' SCREAMING_SNAKE_CASE_ : Any = [2, 413, 615, 114, 3, 1971, 113, 1679, 10710, 107, 1] SCREAMING_SNAKE_CASE_ : List[str] = tokenizer([raw_input_str] , return_tensors=lowercase_).input_ids[0] self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 96103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE_ : Optional[Any] = '''To ensure a smooth flow of bank resolutions.''' SCREAMING_SNAKE_CASE_ : Tuple = [413, 615, 114, 2291, 1971, 113, 1679, 10710, 107, 1] SCREAMING_SNAKE_CASE_ : Tuple = tokenizer([raw_input_str] , return_tensors=lowercase_).input_ids[0] self.assertListEqual(lowercase_ , lowercase_) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3]) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = ['''This is going to be way too long.''' * 150, '''short example'''] SCREAMING_SNAKE_CASE_ : List[Any] = ['''not super long but more than 5 tokens''', '''tiny'''] SCREAMING_SNAKE_CASE_ : Dict = self._large_tokenizer(lowercase_ , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''') SCREAMING_SNAKE_CASE_ : int = self._large_tokenizer( text_target=lowercase_ , max_length=5 , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''') assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(lowercase_) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = {'''input_ids''': [[38979, 143, 18485, 606, 130, 26669, 87686, 121, 54189, 1129, 111, 26669, 87686, 121, 9114, 14787, 121, 13249, 158, 592, 956, 121, 14621, 31576, 143, 62613, 108, 9688, 930, 43430, 11562, 62613, 304, 108, 11443, 897, 108, 9314, 17415, 63399, 108, 11443, 7614, 18316, 118, 4284, 7148, 12430, 143, 1400, 25703, 158, 111, 4284, 7148, 11772, 143, 21297, 1064, 158, 122, 204, 3506, 1754, 1133, 14787, 1581, 115, 33224, 4482, 111, 1355, 110, 29173, 317, 50833, 108, 20147, 94665, 111, 77198, 107, 1], [110, 62613, 117, 638, 112, 1133, 121, 20098, 1355, 79050, 13872, 135, 1596, 53541, 1352, 141, 13039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 18289, 17780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , ) @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = PegasusTokenizer __UpperCamelCase = PegasusTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_ : Optional[int] = PegasusTokenizer(lowercase_ , offset=0 , mask_token_sent=lowercase_ , mask_token='''[MASK]''') tokenizer.save_pretrained(self.tmpdirname) @cached_property def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''') def _SCREAMING_SNAKE_CASE ( self : List[str] , **lowercase_ : str): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Dict): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = self.tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) SCREAMING_SNAKE_CASE_ : List[Any] = rust_tokenizer([raw_input_str] , return_tensors=lowercase_ , add_special_tokens=lowercase_).input_ids[0] SCREAMING_SNAKE_CASE_ : List[Any] = py_tokenizer([raw_input_str] , return_tensors=lowercase_ , add_special_tokens=lowercase_).input_ids[0] self.assertListEqual(lowercase_ , lowercase_) @require_torch def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = ['''This is going to be way too long.''' * 1000, '''short example'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''not super long but more than 5 tokens''', '''tiny'''] SCREAMING_SNAKE_CASE_ : List[Any] = self._large_tokenizer(lowercase_ , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''') SCREAMING_SNAKE_CASE_ : Optional[Any] = self._large_tokenizer( text_target=lowercase_ , max_length=5 , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''') assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(lowercase_) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._large_tokenizer(lowercase_).input_ids self.assertListEqual( lowercase_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 25016, 3137, 464, 109, 26955, 3137, 1] , )
318
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _A (__a , __a , __a=1e-12 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T SCREAMING_SNAKE_CASE_ : List[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T return jnp.matmul(__a , norm_emb_a.T ) class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxCLIPVisionModule(self.config.vision_config) SCREAMING_SNAKE_CASE_ : Tuple = nn.Dense(self.config.projection_dim , use_bias=lowercase_ , dtype=self.dtype) SCREAMING_SNAKE_CASE_ : List[str] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Dict = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,)) def __call__( self : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.vision_model(lowercase_)[1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.visual_projection(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.special_care_embeds) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs SCREAMING_SNAKE_CASE_ : Tuple = 0.0 SCREAMING_SNAKE_CASE_ : Dict = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment SCREAMING_SNAKE_CASE_ : Optional[int] = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : List[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=lowercase_) # Use a lower threshold if an image has any special care concept SCREAMING_SNAKE_CASE_ : Dict = is_special_care * 0.01 SCREAMING_SNAKE_CASE_ : str = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment SCREAMING_SNAKE_CASE_ : Any = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : Dict = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = CLIPConfig __UpperCamelCase = "clip_input" __UpperCamelCase = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Union[str, Any] , lowercase_ : CLIPConfig , lowercase_ : Optional[Tuple] = None , lowercase_ : int = 0 , lowercase_ : jnp.dtype = jnp.floataa , lowercase_ : bool = True , **lowercase_ : Any , ): '''simple docstring''' if input_shape is None: SCREAMING_SNAKE_CASE_ : List[str] = (1, 224, 224, 3) SCREAMING_SNAKE_CASE_ : List[Any] = self.module_class(config=lowercase_ , dtype=lowercase_ , **lowercase_) super().__init__(lowercase_ , lowercase_ , input_shape=lowercase_ , seed=lowercase_ , dtype=lowercase_ , _do_init=_do_init) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : jax.random.KeyArray , lowercase_ : Tuple , lowercase_ : FrozenDict = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = jax.random.normal(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = jax.random.split(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = {'''params''': params_rng, '''dropout''': dropout_rng} SCREAMING_SNAKE_CASE_ : List[Any] = self.module.init(lowercase_ , lowercase_)['''params'''] return random_params def __call__( self : List[Any] , lowercase_ : List[str] , lowercase_ : dict = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = jnp.transpose(lowercase_ , (0, 2, 3, 1)) return self.module.apply( {'''params''': params or self.params} , jnp.array(lowercase_ , dtype=jnp.floataa) , rngs={} , )
318
1
"""simple docstring""" import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def _A (__a ) -> str: """simple docstring""" if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , lowercase_ : nn.Module , lowercase_ : int): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : Dict = module SCREAMING_SNAKE_CASE_ : Dict = nn.Sequential( nn.Linear(module.in_features , lowercase_ , bias=lowercase_) , nn.Linear(lowercase_ , module.out_features , bias=lowercase_) , ) SCREAMING_SNAKE_CASE_ : str = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=lowercase_) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Any , *lowercase_ : Dict , **lowercase_ : Any): '''simple docstring''' return self.module(lowercase_ , *lowercase_ , **lowercase_) + self.adapter(lowercase_) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = "bigscience/bloom-1b7" # Constant values __UpperCamelCase = 2.1_0_9_6_5_9_5_5_2_6_9_2_5_7_4 __UpperCamelCase = "Hello my name is" __UpperCamelCase = set() EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I" ) EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n" ) EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University" ) __UpperCamelCase = 1_0 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = AutoTokenizer.from_pretrained(self.model_name) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE_ : Dict = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='''auto''') SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowercase_ , device_map='''auto''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.model_abit.config self.assertTrue(hasattr(lowercase_ , '''quantization_config''')) SCREAMING_SNAKE_CASE_ : int = config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[Any] = config.to_diff_dict() SCREAMING_SNAKE_CASE_ : Dict = config.to_json_string() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE_ : str = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE_ : List[Any] = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(lowercase_ , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.tokenizer(self.input_text , return_tensors='''pt''') SCREAMING_SNAKE_CASE_ : int = self.model_abit.generate(input_ids=encoded_input['''input_ids'''].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowercase_) , self.EXPECTED_OUTPUTS) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = BitsAndBytesConfig() SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=lowercase_ , device_map='''auto''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer(self.input_text , return_tensors='''pt''') SCREAMING_SNAKE_CASE_ : Optional[int] = model_abit_from_config.generate( input_ids=encoded_input['''input_ids'''].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowercase_) , self.EXPECTED_OUTPUTS) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = BitsAndBytesConfig() with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : Any = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=lowercase_ , load_in_abit=lowercase_ , device_map='''auto''' , bnb_abit_quant_type='''nf4''' , ) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' with self.assertRaises(lowercase_): # Tries with `str` self.model_abit.to('''cpu''') with self.assertRaises(lowercase_): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(lowercase_): # Tries with a `device` self.model_abit.to(torch.device('''cuda:0''')) with self.assertRaises(lowercase_): # Tries with a `device` self.model_abit.float() with self.assertRaises(lowercase_): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE_ : Any = self.tokenizer(self.input_text , return_tensors='''pt''') SCREAMING_SNAKE_CASE_ : Dict = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_fpaa.generate(input_ids=encoded_input['''input_ids'''].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_fpaa.to('''cpu''') # Check this does not throw an error SCREAMING_SNAKE_CASE_ : Tuple = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE_ : int = self.model_fpaa.float() def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = AutoModelForSeqaSeqLM.from_pretrained('''t5-small''' , load_in_abit=lowercase_ , device_map='''auto''') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''t5-small''' SCREAMING_SNAKE_CASE_ : str = '''google/flan-t5-small''' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE_ : str = '''Translate in German: Hello, my dog is cute''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE_ : List[str] = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE_ : List[str] = None # test with `t5-small` SCREAMING_SNAKE_CASE_ : Union[str, Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowercase_ , device_map='''auto''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(self.input_text , return_tensors='''pt''').to(0) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.generate(**lowercase_) # test with `flan-t5-small` SCREAMING_SNAKE_CASE_ : Dict = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=lowercase_ , device_map='''auto''') SCREAMING_SNAKE_CASE_ : str = self.tokenizer(self.input_text , return_tensors='''pt''').to(0) SCREAMING_SNAKE_CASE_ : Dict = model.generate(**lowercase_) SCREAMING_SNAKE_CASE_ : int = modules def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE_ : List[Any] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowercase_ , device_map='''auto''') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(self.input_text , return_tensors='''pt''').to(0) SCREAMING_SNAKE_CASE_ : int = model.generate(**lowercase_) # test with `flan-t5-small` SCREAMING_SNAKE_CASE_ : Tuple = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=lowercase_ , device_map='''auto''') SCREAMING_SNAKE_CASE_ : str = self.tokenizer(self.input_text , return_tensors='''pt''').to(0) SCREAMING_SNAKE_CASE_ : List[Any] = model.generate(**lowercase_) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' super().setUp() # model_name SCREAMING_SNAKE_CASE_ : Optional[int] = '''bigscience/bloom-560m''' SCREAMING_SNAKE_CASE_ : Any = '''t5-small''' # Different types of model SCREAMING_SNAKE_CASE_ : str = AutoModel.from_pretrained(self.model_name , load_in_abit=lowercase_ , device_map='''auto''') # Sequence classification model SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=lowercase_ , device_map='''auto''') # CausalLM model SCREAMING_SNAKE_CASE_ : List[Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowercase_ , device_map='''auto''') # Seq2seq model SCREAMING_SNAKE_CASE_ : List[Any] = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=lowercase_ , device_map='''auto''') def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' super().setUp() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' del self.pipe gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = pipeline( '''text-generation''' , model=self.model_name , model_kwargs={'''device_map''': '''auto''', '''load_in_4bit''': True, '''torch_dtype''': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE_ : int = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['''generated_text'''] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' super().setUp() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=lowercase_ , device_map='''balanced''') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer(self.input_text , return_tensors='''pt''') # Second real batch SCREAMING_SNAKE_CASE_ : Optional[Any] = model_parallel.generate(input_ids=encoded_input['''input_ids'''].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=lowercase_) , self.EXPECTED_OUTPUTS) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = '''facebook/opt-350m''' super().setUp() def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' if version.parse(importlib.metadata.version('''bitsandbytes''')) < version.parse('''0.37.0'''): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowercase_) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE_ : Optional[Any] = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE_ : Dict = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(lowercase_)): SCREAMING_SNAKE_CASE_ : int = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE_ : str = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE_ : str = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer('''Test batch ''' , return_tensors='''pt''').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE_ : List[Any] = model.forward(**lowercase_) out.logits.norm().backward() for module in model.modules(): if isinstance(lowercase_ , lowercase_): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(lowercase_ , nn.Embedding): self.assertTrue(module.weight.grad is None) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "gpt2-xl" __UpperCamelCase = 3.3_1_9_1_8_5_4_8_5_4_1_5_2_1_8_7
318
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = data SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None def _A () -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ : List[Any] = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() SCREAMING_SNAKE_CASE_ : Union[str, Any] = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = q.get() SCREAMING_SNAKE_CASE_ : List[str] = f'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : Optional[int] = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : List[str] = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ : str = f'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : str = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : Any = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : int = right_node q.put(__a ) raise def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Tuple = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : str = [] while not q.empty(): SCREAMING_SNAKE_CASE_ : List[str] = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ : Tuple = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ : str = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Any = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.left SCREAMING_SNAKE_CASE_ : Any = stack.pop() print(n.data , end=''',''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = [], [] SCREAMING_SNAKE_CASE_ : List[Any] = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ : List[str] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def _A (__a = "" , __a=50 , __a="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = divmod(width - len(__a ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase_ : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
318
1
"""simple docstring""" from __future__ import annotations UpperCAmelCase_ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase_ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase_ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _A (__a , __a , __a , __a ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _A (__a ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _A (__a ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__a ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__a , __a , __a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = digit if sudoku(__a ) is not None: return grid SCREAMING_SNAKE_CASE_ : Any = 0 return None def _A (__a ) -> None: """simple docstring""" for row in grid: for cell in row: print(__a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") UpperCAmelCase_ : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
318
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = "ssube/stable-diffusion-x4-upscaler-onnx" def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any]=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, 3, 128, 128) , rng=random.Random(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Dict = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Tuple = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array( [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : List[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : int = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[int] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array( [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ort.SessionOptions() SCREAMING_SNAKE_CASE_ : Optional[int] = False return options def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Optional[int] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) SCREAMING_SNAKE_CASE_ : Tuple = LMSDiscreteScheduler.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , subfolder='''scheduler''') SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , scheduler=lowercase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : int = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=20 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Dict = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array( [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2
318
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) def _A (__a ) -> List[int]: """simple docstring""" if isinstance(__a , np.ndarray ): return list(tensor.shape ) SCREAMING_SNAKE_CASE_ : str = tf.shape(__a ) if tensor.shape == tf.TensorShape(__a ): return dynamic SCREAMING_SNAKE_CASE_ : Tuple = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(__a )] def _A (__a , __a = None , __a = None ) -> tf.Tensor: """simple docstring""" return tf.nn.softmax(logits=logits + 1e-9 , axis=__a , name=__a ) def _A (__a , __a , __a , __a=1e-5 , __a=-1 ) -> str: """simple docstring""" if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__a , __a ): raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.''' ) # Get mean and variance on the axis to be normalized SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = tf.nn.moments(__a , axes=[axis] , keepdims=__a ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis SCREAMING_SNAKE_CASE_ : str = [1] * inputs.shape.rank SCREAMING_SNAKE_CASE_ : str = shape_list(__a )[axis] SCREAMING_SNAKE_CASE_ : Dict = tf.reshape(__a , __a ) SCREAMING_SNAKE_CASE_ : str = tf.reshape(__a , __a ) # Compute layer normalization using the batch_normalization # function. SCREAMING_SNAKE_CASE_ : str = tf.nn.batch_normalization( __a , __a , __a , offset=__a , scale=__a , variance_epsilon=__a , ) return outputs def _A (__a , __a=0 , __a=-1 ) -> Tuple: """simple docstring""" if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input SCREAMING_SNAKE_CASE_ : Any = tf.shape(__a ) SCREAMING_SNAKE_CASE_ : str = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) SCREAMING_SNAKE_CASE_ : List[str] = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(__a , __a ) def _A (__a ) -> tf.Tensor: """simple docstring""" if not isinstance(__a , tf.Tensor ): SCREAMING_SNAKE_CASE_ : List[Any] = tf.convert_to_tensor(__a ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: SCREAMING_SNAKE_CASE_ : List[str] = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: SCREAMING_SNAKE_CASE_ : List[Any] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) SCREAMING_SNAKE_CASE_ : List[str] = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _A (__a , __a , __a = "input_ids" ) -> None: """simple docstring""" tf.debugging.assert_less( __a , tf.cast(__a , dtype=tensor.dtype ) , message=( f'The maximum value of {tensor_name} ({tf.math.reduce_max(__a )}) must be smaller than the embedding ' f'layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.' ) , ) def _A (__a , __a , __a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. SCREAMING_SNAKE_CASE_ : List[str] = [x for x in data if len(__a ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( '''The following attributes cannot be saved to HDF5 file because ''' f'they are larger than {HDF5_OBJECT_HEADER_LIMIT} ' f'bytes: {bad_attributes}' ) SCREAMING_SNAKE_CASE_ : int = np.asarray(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array_split(__a , __a ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = np.array_split(__a , __a ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(__a ): SCREAMING_SNAKE_CASE_ : Any = chunk_data else: SCREAMING_SNAKE_CASE_ : List[str] = data def _A (__a , __a ) -> str: """simple docstring""" if name in group.attrs: SCREAMING_SNAKE_CASE_ : List[str] = [n.decode('''utf8''' ) if hasattr(__a , '''decode''' ) else n for n in group.attrs[name]] else: SCREAMING_SNAKE_CASE_ : Optional[int] = [] SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('''utf8''' ) if hasattr(__a , '''decode''' ) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]] ) chunk_id += 1 return data def _A (__a ) -> List[str]: """simple docstring""" def _expand_single_ad_tensor(__a ): if isinstance(__a , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(__a , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , __a )
318
"""simple docstring""" from scipy.stats import pearsonr import datasets UpperCAmelCase_ : List[Any] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ UpperCAmelCase_ : Optional[int] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ UpperCAmelCase_ : Tuple = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float'''), '''references''': datasets.Value('''float'''), }) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=False): '''simple docstring''' if return_pvalue: SCREAMING_SNAKE_CASE_ : int = pearsonr(lowercase_ , lowercase_) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(lowercase_ , lowercase_)[0])}
318
1
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = "ssube/stable-diffusion-x4-upscaler-onnx" def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any]=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, 3, 128, 128) , rng=random.Random(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Dict = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Tuple = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array( [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : List[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : int = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[int] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array( [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ort.SessionOptions() SCREAMING_SNAKE_CASE_ : Optional[int] = False return options def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Optional[int] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) SCREAMING_SNAKE_CASE_ : Tuple = LMSDiscreteScheduler.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , subfolder='''scheduler''') SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , scheduler=lowercase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : int = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=20 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Dict = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array( [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2
318
"""simple docstring""" import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class lowerCAmelCase__ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any , lowercase_ : Dict[str, int] , lowercase_ : List[str] , lowercase_ : int = None , lowercase_ : int = None): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : str = pad_token_id SCREAMING_SNAKE_CASE_ : Optional[int] = max_length SCREAMING_SNAKE_CASE_ : Dict = vocab SCREAMING_SNAKE_CASE_ : Dict = merges SCREAMING_SNAKE_CASE_ : Union[str, Any] = BytePairTokenizer(lowercase_ , lowercase_ , sequence_length=lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : GPTaTokenizer , *lowercase_ : Optional[Any] , **lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = [''' '''.join(lowercase_) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE_ : str = tokenizer.get_vocab() return cls(lowercase_ , lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowercase_ : Union[str, os.PathLike] , *lowercase_ : List[str] , **lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = GPTaTokenizer.from_pretrained(lowercase_ , *lowercase_ , **lowercase_) return cls.from_tokenizer(lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : List[Any]): '''simple docstring''' return cls(**lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[Any] , lowercase_ : int = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.tf_tokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.ones_like(lowercase_) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = pad_model_inputs( lowercase_ , max_seq_length=lowercase_ , pad_value=self.pad_token_id) return {"attention_mask": attention_mask, "input_ids": input_ids}
318
1
"""simple docstring""" import random class lowerCAmelCase__ : '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ord(lowercase_) for i in text] SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] for i in plain: SCREAMING_SNAKE_CASE_ : Tuple = random.randint(1 , 300) SCREAMING_SNAKE_CASE_ : int = (i + k) * k cipher.append(lowercase_) key.append(lowercase_) return cipher, key @staticmethod def _SCREAMING_SNAKE_CASE ( lowercase_ : list[int] , lowercase_ : list[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [] for i in range(len(lowercase_)): SCREAMING_SNAKE_CASE_ : int = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(lowercase_)) return "".join(lowercase_) if __name__ == "__main__": UpperCAmelCase_ , UpperCAmelCase_ : Tuple = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
318
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) SCREAMING_SNAKE_CASE_ : Dict = { '''do_resize''': True, '''size''': {'''height''': 224, '''width''': 224}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], '''do_convert_rgb''': True, } SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , lowercase_) with open(self.image_processor_file , '''w''' , encoding='''utf-8''') as fp: json.dump(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , **lowercase_ : str): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , **lowercase_ : List[Any]): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , **lowercase_ : str): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] SCREAMING_SNAKE_CASE_ : Dict = [Image.fromarray(np.moveaxis(lowercase_ , 0 , -1)) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_slow.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : Any = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_fast.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , lowercase_) self.assertIsInstance(processor_fast.tokenizer , lowercase_) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , lowercase_) self.assertIsInstance(processor_fast.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_image_processor(do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=lowercase_) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , lowercase_) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Any = image_processor(lowercase_ , return_tensors='''np''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor(images=lowercase_ , return_tensors='''np''') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : str = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Optional[Any] = processor(text=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer(lowercase_) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : int = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']) # test if it raises when no input is passed with pytest.raises(lowercase_): processor() def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_ : Optional[int] = processor.batch_decode(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.batch_decode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Dict = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Dict = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Dict = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
318
1
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Dict = 5 # Realm tok SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(self.tmpdirname , '''realm_tokenizer''') os.makedirs(lowercase_ , exist_ok=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(lowercase_ , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) SCREAMING_SNAKE_CASE_ : str = os.path.join(self.tmpdirname , '''realm_block_records''') os.makedirs(lowercase_ , exist_ok=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''')) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = RealmConfig(num_block_records=self.num_block_records) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], }) return dataset def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=lowercase_ , ) return block_records def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.get_config() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_dummy_retriever() SCREAMING_SNAKE_CASE_ : Optional[int] = retriever.tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = np.array([0, 3] , dtype='''long''') SCREAMING_SNAKE_CASE_ : str = tokenizer(['''Test question''']).input_ids SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer( ['''the fourth'''] , add_special_tokens=lowercase_ , return_token_type_ids=lowercase_ , return_attention_mask=lowercase_ , ).input_ids SCREAMING_SNAKE_CASE_ : Optional[int] = config.reader_seq_len SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = retriever( lowercase_ , lowercase_ , answer_ids=lowercase_ , max_length=lowercase_ , return_tensors='''np''') self.assertEqual(len(lowercase_) , 2) self.assertEqual(len(lowercase_) , 2) self.assertEqual(len(lowercase_) , 2) self.assertEqual(concat_inputs.input_ids.shape , (2, 10)) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10)) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10)) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10)) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.get_config() SCREAMING_SNAKE_CASE_ : str = self.get_dummy_retriever() SCREAMING_SNAKE_CASE_ : Optional[Any] = retriever.tokenizer SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([0, 3, 5] , dtype='''long''') SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer(['''Test question''']).input_ids SCREAMING_SNAKE_CASE_ : int = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=lowercase_ , return_token_type_ids=lowercase_ , return_attention_mask=lowercase_ , ).input_ids SCREAMING_SNAKE_CASE_ : Optional[int] = config.reader_seq_len SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = retriever( lowercase_ , lowercase_ , answer_ids=lowercase_ , max_length=lowercase_ , return_tensors='''np''') self.assertEqual([False, True, True] , lowercase_) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , lowercase_) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''')) # Test local path SCREAMING_SNAKE_CASE_ : Tuple = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''')) self.assertEqual(retriever.block_records[0] , b'''This is the first record''') # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''') as mock_hf_hub_download: SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''') , _REALM_BLOCK_RECORDS_FILENAME) SCREAMING_SNAKE_CASE_ : Tuple = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''') self.assertEqual(retriever.block_records[0] , b'''This is the first record''')
318
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "rwkv" __UpperCamelCase = {"max_position_embeddings": "context_length"} def __init__( self : Union[str, Any] , lowercase_ : Any=50277 , lowercase_ : str=1024 , lowercase_ : List[str]=4096 , lowercase_ : Optional[Any]=32 , lowercase_ : Any=None , lowercase_ : Any=None , lowercase_ : List[Any]=1e-5 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=0 , lowercase_ : int=6 , lowercase_ : Tuple=False , lowercase_ : Any=True , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Any = context_length SCREAMING_SNAKE_CASE_ : int = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size SCREAMING_SNAKE_CASE_ : int = intermediate_size if intermediate_size is not None else 4 * hidden_size SCREAMING_SNAKE_CASE_ : int = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : Optional[int] = rescale_every SCREAMING_SNAKE_CASE_ : Dict = use_cache SCREAMING_SNAKE_CASE_ : Dict = bos_token_id SCREAMING_SNAKE_CASE_ : Any = eos_token_id super().__init__( tie_word_embeddings=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_)
318
1
"""simple docstring""" import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = {} SCREAMING_SNAKE_CASE_ : str = tokenizer(example['''content'''] , truncation=__a )['''input_ids'''] SCREAMING_SNAKE_CASE_ : Union[str, Any] = len(example['''content'''] ) / len(output['''input_ids'''] ) return output UpperCAmelCase_ : Union[str, Any] = HfArgumentParser(PretokenizationArguments) UpperCAmelCase_ : List[str] = parser.parse_args() if args.num_workers is None: UpperCAmelCase_ : str = multiprocessing.cpu_count() UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_dir) UpperCAmelCase_ : List[Any] = time.time() UpperCAmelCase_ : Tuple = load_dataset(args.dataset_name, split="""train""") print(f'''Dataset loaded in {time.time()-t_start:.2f}s''') UpperCAmelCase_ : Optional[Any] = time.time() UpperCAmelCase_ : Dict = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ """repo_name""", """path""", """copies""", """size""", """content""", """license""", """hash""", """line_mean""", """line_max""", """alpha_frac""", """autogenerated""", ], ) print(f'''Dataset tokenized in {time.time()-t_start:.2f}s''') UpperCAmelCase_ : str = time.time() ds.push_to_hub(args.tokenized_data_repo) print(f'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
318
"""simple docstring""" UpperCAmelCase_ : Optional[int] = 8.3_1_4_4_5_9_8 def _A (__a , __a ) -> float: """simple docstring""" if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example UpperCAmelCase_ : str = 300 UpperCAmelCase_ : str = 28 UpperCAmelCase_ : Any = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
318
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. UpperCAmelCase_ : Union[str, Any] = abspath(join(dirname(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 _A (__a ) -> Union[str, Any]: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def _A (__a ) -> Any: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE_ : Optional[Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a , id=__a )
318
"""simple docstring""" import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList UpperCAmelCase_ : Union[str, Any] = ["""\nclass""", """\ndef""", """\n#""", """\n@""", """\nprint""", """\nif"""] class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : int=None , lowercase_ : Dict=1): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = dataset SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase_) if n_tasks is None else n_tasks SCREAMING_SNAKE_CASE_ : Optional[int] = n_copies def __iter__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for task in range(self.n_tasks): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip()) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowercase_ , padding=lowercase_ , return_tensors='''pt''') for task in range(self.n_tasks): for _ in range(self.n_copies): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = start_length SCREAMING_SNAKE_CASE_ : List[Any] = eof_strings SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer def __call__( self : Optional[int] , lowercase_ : Any , lowercase_ : int , **lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.tokenizer.batch_decode(input_ids[:, self.start_length :]) SCREAMING_SNAKE_CASE_ : Tuple = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings)) return all(lowercase_) def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.split('''(%s)''' % '''|'''.join(__a ) , __a ) # last string should be "" return "".join(string_list[:-2] ) def _A (__a , __a , __a , __a , __a , __a=20 , **__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = defaultdict(__a ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__a ) ): with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] = batch['''ids'''].shape[-1] SCREAMING_SNAKE_CASE_ : Tuple = accelerator.unwrap_model(__a ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']] , num_return_sequences=__a , **__a ) # each task is generated batch_size times SCREAMING_SNAKE_CASE_ : List[Any] = batch['''task_id'''].repeat(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.pad_across_processes( __a , dim=1 , pad_index=tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) SCREAMING_SNAKE_CASE_ : int = generated_tokens.cpu().numpy() SCREAMING_SNAKE_CASE_ : Optional[Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__a , __a ): gen_token_dict[task].append(__a ) SCREAMING_SNAKE_CASE_ : int = [[] for _ in range(__a )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) code_gens[task].append(remove_last_block(__a ) ) return code_gens def _A () -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = HfArgumentParser(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric SCREAMING_SNAKE_CASE_ : Any = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing SCREAMING_SNAKE_CASE_ : str = '''false''' if args.num_workers is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() set_seed(args.seed , device_specific=__a ) # Load model and tokenizer SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.eos_token SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings SCREAMING_SNAKE_CASE_ : List[str] = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0 , __a , __a )] ), } # Load evaluation dataset and metric SCREAMING_SNAKE_CASE_ : Optional[int] = load_dataset('''openai_humaneval''' ) SCREAMING_SNAKE_CASE_ : str = load_metric('''code_eval''' ) SCREAMING_SNAKE_CASE_ : int = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) SCREAMING_SNAKE_CASE_ : List[str] = args.n_samples // args.batch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = TokenizedDataset(__a , human_eval['''test'''] , n_copies=__a , n_tasks=__a ) # do not confuse args.batch_size, which is actually the num_return_sequences SCREAMING_SNAKE_CASE_ : Optional[int] = DataLoader(__a , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: SCREAMING_SNAKE_CASE_ : Any = code_eval_metric.compute(references=[''''''] , predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = accelerator.prepare(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = complete_code( __a , __a , __a , __a , n_tasks=__a , batch_size=args.batch_size , **__a , ) if accelerator.is_main_process: SCREAMING_SNAKE_CASE_ : int = [] for task in tqdm(range(__a ) ): SCREAMING_SNAKE_CASE_ : Tuple = human_eval['''test'''][task]['''test'''] SCREAMING_SNAKE_CASE_ : Tuple = f'check({human_eval["test"][task]["entry_point"]})' references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = code_eval_metric.compute( references=__a , predictions=__a , num_workers=args.num_workers ) print(f'Results: {pass_at_k}' ) # Save results to json file with open(args.output_file , '''w''' ) as fp: json.dump(__a , __a ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
318
1
"""simple docstring""" from __future__ import annotations import os from typing import Any import requests UpperCAmelCase_ : Optional[Any] = """https://api.github.com""" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user UpperCAmelCase_ : int = BASE_URL + """/user""" # https://github.com/settings/tokens UpperCAmelCase_ : Union[str, Any] = os.environ.get("""USER_TOKEN""", """""") def _A (__a ) -> dict[Any, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = { '''Authorization''': f'token {auth_token}', '''Accept''': '''application/vnd.github.v3+json''', } return requests.get(__a , headers=__a ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f'''{key}: {value}''') else: raise ValueError("""'USER_TOKEN' field cannot be empty.""")
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "feature_extractor"] __UpperCamelCase = "TvltImageProcessor" __UpperCamelCase = "TvltFeatureExtractor" def __init__( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(image_processor=lowercase_ , feature_extractor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = feature_extractor def __call__( self : Any , lowercase_ : str=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : str=None , lowercase_ : int=False , lowercase_ : Union[str, Any]=False , *lowercase_ : List[Any] , **lowercase_ : List[str] , ): '''simple docstring''' if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''') SCREAMING_SNAKE_CASE_ : Any = None if images is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor(lowercase_ , mask_pixel=lowercase_ , *lowercase_ , **lowercase_) if images_mixed is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , is_mixed=lowercase_ , *lowercase_ , **lowercase_) if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor( lowercase_ , *lowercase_ , sampling_rate=lowercase_ , mask_audio=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {} if audio is not None: output_dict.update(lowercase_) if images is not None: output_dict.update(lowercase_) if images_mixed_dict is not None: output_dict.update(lowercase_) return output_dict @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
318
1
"""simple docstring""" def _A (__a = 10 , __a = 22 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = range(1 , __a ) SCREAMING_SNAKE_CASE_ : Tuple = range(1 , __a ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "SpeechT5FeatureExtractor" __UpperCamelCase = "SpeechT5Tokenizer" def __init__( self : Any , lowercase_ : Dict , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(lowercase_ , lowercase_) def __call__( self : List[Any] , *lowercase_ : List[Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''audio''' , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.pop('''text''' , lowercase_) SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('''text_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''audio_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''sampling_rate''' , lowercase_) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''') if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''') if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''') if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor(lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) elif text is not None: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = None if audio_target is not None: SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extractor(audio_target=lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = targets['''input_values'''] elif text_target is not None: SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : int = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = labels SCREAMING_SNAKE_CASE_ : Optional[Any] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Any = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : Tuple , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''input_values''' , lowercase_) SCREAMING_SNAKE_CASE_ : int = kwargs.pop('''input_ids''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''labels''' , lowercase_) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''') if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''') if input_values is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) elif input_ids is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.pad(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : List[Any] = None if labels is not None: if "input_ids" in labels or (isinstance(lowercase_ , lowercase_) and "input_ids" in labels[0]): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer.pad(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Dict = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.feature_size SCREAMING_SNAKE_CASE_ : Optional[int] = self.feature_extractor.num_mel_bins SCREAMING_SNAKE_CASE_ : str = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : str = feature_size_hack SCREAMING_SNAKE_CASE_ : Dict = targets['''input_values'''] else: SCREAMING_SNAKE_CASE_ : List[Any] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Dict = labels SCREAMING_SNAKE_CASE_ : List[str] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowercase_ : Optional[int] , **lowercase_ : Tuple): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *lowercase_ : Dict , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_)
318
1
"""simple docstring""" def _A (__a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = len(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = sum(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE_ : Dict = True for i in range(1 , s + 1 ): SCREAMING_SNAKE_CASE_ : List[str] = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): SCREAMING_SNAKE_CASE_ : Any = dp[i][j - 1] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE_ : List[Any] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: SCREAMING_SNAKE_CASE_ : Union[str, Any] = s - 2 * j break return diff
318
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.inf def set_batch_size(__a ) -> None: nonlocal batch_size if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__a , __a ) and feature.dtype == "binary": SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__a , __a ) return None if batch_size is np.inf else batch_size class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , lowercase_ : NestedDataStructureLike[PathLike] , lowercase_ : Optional[NamedSplit] = None , lowercase_ : Optional[Features] = None , lowercase_ : str = None , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : Optional[int] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , split=lowercase_ , features=lowercase_ , cache_dir=lowercase_ , keep_in_memory=lowercase_ , streaming=lowercase_ , num_proc=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = path_or_paths if isinstance(lowercase_ , lowercase_) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_ : Any = _PACKAGED_DATASETS_MODULES['''parquet'''][1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = Parquet( cache_dir=lowercase_ , data_files=lowercase_ , features=lowercase_ , hash=lowercase_ , **lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE_ : str = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None self.builder.download_and_prepare( download_config=lowercase_ , download_mode=lowercase_ , verification_mode=lowercase_ , base_path=lowercase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_ : Any = self.builder.as_dataset( split=self.split , verification_mode=lowercase_ , in_memory=self.keep_in_memory) return dataset class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Dataset , lowercase_ : Union[PathLike, BinaryIO] , lowercase_ : Optional[int] = None , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = dataset SCREAMING_SNAKE_CASE_ : Dict = path_or_buf SCREAMING_SNAKE_CASE_ : List[Any] = batch_size or get_writer_batch_size(dataset.features) SCREAMING_SNAKE_CASE_ : Any = parquet_writer_kwargs def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , '''wb+''') as buffer: SCREAMING_SNAKE_CASE_ : Optional[Any] = self._write(file_obj=lowercase_ , batch_size=lowercase_ , **self.parquet_writer_kwargs) else: SCREAMING_SNAKE_CASE_ : str = self._write(file_obj=self.path_or_buf , batch_size=lowercase_ , **self.parquet_writer_kwargs) return written def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : BinaryIO , lowercase_ : int , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = parquet_writer_kwargs.pop('''path_or_buf''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dataset.features.arrow_schema SCREAMING_SNAKE_CASE_ : Tuple = pq.ParquetWriter(lowercase_ , schema=lowercase_ , **lowercase_) for offset in logging.tqdm( range(0 , len(self.dataset) , lowercase_) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): SCREAMING_SNAKE_CASE_ : List[Any] = query_table( table=self.dataset._data , key=slice(lowercase_ , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(lowercase_) written += batch.nbytes writer.close() return written
318
1
"""simple docstring""" import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : '''simple docstring''' @staticmethod def _SCREAMING_SNAKE_CASE ( *lowercase_ : List[str] , **lowercase_ : str): '''simple docstring''' pass @is_pipeline_test @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @require_torch def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) SCREAMING_SNAKE_CASE_ : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_classifier(lowercase_ , candidate_labels=['''a''', '''b''', '''c''']) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(lowercase_) , [ [{'''score''': 0.3_33, '''label''': '''a'''}, {'''score''': 0.3_33, '''label''': '''b'''}, {'''score''': 0.3_33, '''label''': '''c'''}], [{'''score''': 0.3_33, '''label''': '''a'''}, {'''score''': 0.3_33, '''label''': '''c'''}, {'''score''': 0.3_33, '''label''': '''b'''}], ] , ) SCREAMING_SNAKE_CASE_ : List[Any] = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2) self.assertEqual( nested_simplify(lowercase_) , [ [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], ] , ) @require_tf def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''') SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') SCREAMING_SNAKE_CASE_ : int = image_classifier(lowercase_ , candidate_labels=['''a''', '''b''', '''c''']) self.assertEqual( nested_simplify(lowercase_) , [{'''score''': 0.3_33, '''label''': '''a'''}, {'''score''': 0.3_33, '''label''': '''b'''}, {'''score''': 0.3_33, '''label''': '''c'''}] , ) SCREAMING_SNAKE_CASE_ : List[Any] = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2) self.assertEqual( nested_simplify(lowercase_) , [ [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], [ {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, {'''score''': 0.3_33, '''label''': ANY(lowercase_)}, ], ] , ) @slow @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE_ : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') SCREAMING_SNAKE_CASE_ : int = image_classifier(lowercase_ , candidate_labels=['''cat''', '''plane''', '''remote''']) self.assertEqual( nested_simplify(lowercase_) , [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2) self.assertEqual( nested_simplify(lowercase_) , [ [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''') # This is an image of 2 cats with remotes and no planes SCREAMING_SNAKE_CASE_ : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''') SCREAMING_SNAKE_CASE_ : Optional[Any] = image_classifier(lowercase_ , candidate_labels=['''cat''', '''plane''', '''remote''']) self.assertEqual( nested_simplify(lowercase_) , [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ] , ) SCREAMING_SNAKE_CASE_ : List[Any] = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2) self.assertEqual( nested_simplify(lowercase_) , [ [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ], ] * 5 , )
318
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = ["""model.decoder.embed_positions.weights"""] def _A (__a ) -> Dict: """simple docstring""" if "emb" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def _A (__a , __a ) -> Tuple[Dict, Dict]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(state_dict.keys() ) SCREAMING_SNAKE_CASE_ : int = {} for key in keys: SCREAMING_SNAKE_CASE_ : int = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ : int = rename_keys(__a ) if "in_proj_weight" in key: # split fused qkv proj SCREAMING_SNAKE_CASE_ : List[str] = val[:hidden_size, :] SCREAMING_SNAKE_CASE_ : List[str] = val[hidden_size : 2 * hidden_size, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: SCREAMING_SNAKE_CASE_ : int = val else: SCREAMING_SNAKE_CASE_ : Any = val return state_dict, enc_dec_proj_state_dict def _A (__a ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values SCREAMING_SNAKE_CASE_ : Optional[int] = 10_24 SCREAMING_SNAKE_CASE_ : Tuple = 24 SCREAMING_SNAKE_CASE_ : Optional[Any] = 16 elif checkpoint == "medium": SCREAMING_SNAKE_CASE_ : List[str] = 15_36 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : Optional[int] = 24 elif checkpoint == "large": SCREAMING_SNAKE_CASE_ : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : int = 32 else: raise ValueError(f'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' ) SCREAMING_SNAKE_CASE_ : List[Any] = MusicgenDecoderConfig( hidden_size=__a , ffn_dim=hidden_size * 4 , num_hidden_layers=__a , num_attention_heads=__a , ) return config @torch.no_grad() def _A (__a , __a=None , __a=None , __a="cpu" ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = MusicGen.get_pretrained(__a , device=__a ) SCREAMING_SNAKE_CASE_ : Dict = decoder_config_from_checkpoint(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = fairseq_model.lm.state_dict() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = rename_state_dict( __a , hidden_size=decoder_config.hidden_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = TaEncoderModel.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : List[str] = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) SCREAMING_SNAKE_CASE_ : int = MusicgenForCausalLM(__a ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = decoder.load_state_dict(__a , strict=__a ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__a ) if len(__a ) > 0: raise ValueError(f'Missing key(s) in state_dict: {missing_keys}' ) if len(__a ) > 0: raise ValueError(f'Unexpected key(s) in state_dict: {unexpected_keys}' ) # init the composite model SCREAMING_SNAKE_CASE_ : str = MusicgenForConditionalGeneration(text_encoder=__a , audio_encoder=__a , decoder=__a ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__a ) # check we can do a forward pass SCREAMING_SNAKE_CASE_ : Dict = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=__a , decoder_input_ids=__a ).logits if logits.shape != (8, 1, 20_48): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : str = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) SCREAMING_SNAKE_CASE_ : Tuple = MusicgenProcessor(feature_extractor=__a , tokenizer=__a ) # set the appropriate bos/pad token ids SCREAMING_SNAKE_CASE_ : str = 20_48 SCREAMING_SNAKE_CASE_ : List[Any] = 20_48 # set other default generation config params SCREAMING_SNAKE_CASE_ : int = int(30 * audio_encoder.config.frame_rate ) SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Optional[Any] = 3.0 if pytorch_dump_folder is not None: Path(__a ).mkdir(exist_ok=__a ) logger.info(f'Saving model {checkpoint} to {pytorch_dump_folder}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if repo_id: logger.info(f'Pushing model {checkpoint} to {repo_id}' ) model.push_to_hub(__a ) processor.push_to_hub(__a ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) UpperCAmelCase_ : Dict = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
318
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) def _A (__a , __a=False , __a=False , __a=False ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'transformer.blocks.{i}.norm1.weight', f'vilt.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'transformer.blocks.{i}.norm1.bias', f'vilt.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (f'transformer.blocks.{i}.attn.proj.weight', f'vilt.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (f'transformer.blocks.{i}.attn.proj.bias', f'vilt.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'transformer.blocks.{i}.norm2.weight', f'vilt.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'transformer.blocks.{i}.norm2.bias', f'vilt.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append( (f'transformer.blocks.{i}.mlp.fc1.weight', f'vilt.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'transformer.blocks.{i}.mlp.fc1.bias', f'vilt.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'transformer.blocks.{i}.mlp.fc2.weight', f'vilt.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'transformer.blocks.{i}.mlp.fc2.bias', f'vilt.encoder.layer.{i}.output.dense.bias') ) # embeddings rename_keys.extend( [ # text embeddings ('''text_embeddings.word_embeddings.weight''', '''vilt.embeddings.text_embeddings.word_embeddings.weight'''), ( '''text_embeddings.position_embeddings.weight''', '''vilt.embeddings.text_embeddings.position_embeddings.weight''', ), ('''text_embeddings.position_ids''', '''vilt.embeddings.text_embeddings.position_ids'''), ( '''text_embeddings.token_type_embeddings.weight''', '''vilt.embeddings.text_embeddings.token_type_embeddings.weight''', ), ('''text_embeddings.LayerNorm.weight''', '''vilt.embeddings.text_embeddings.LayerNorm.weight'''), ('''text_embeddings.LayerNorm.bias''', '''vilt.embeddings.text_embeddings.LayerNorm.bias'''), # patch embeddings ('''transformer.cls_token''', '''vilt.embeddings.cls_token'''), ('''transformer.patch_embed.proj.weight''', '''vilt.embeddings.patch_embeddings.projection.weight'''), ('''transformer.patch_embed.proj.bias''', '''vilt.embeddings.patch_embeddings.projection.bias'''), ('''transformer.pos_embed''', '''vilt.embeddings.position_embeddings'''), # token type embeddings ('''token_type_embeddings.weight''', '''vilt.embeddings.token_type_embeddings.weight'''), ] ) # final layernorm + pooler rename_keys.extend( [ ('''transformer.norm.weight''', '''vilt.layernorm.weight'''), ('''transformer.norm.bias''', '''vilt.layernorm.bias'''), ('''pooler.dense.weight''', '''vilt.pooler.dense.weight'''), ('''pooler.dense.bias''', '''vilt.pooler.dense.bias'''), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('''vqa_classifier.0.weight''', '''classifier.0.weight'''), ('''vqa_classifier.0.bias''', '''classifier.0.bias'''), ('''vqa_classifier.1.weight''', '''classifier.1.weight'''), ('''vqa_classifier.1.bias''', '''classifier.1.bias'''), ('''vqa_classifier.3.weight''', '''classifier.3.weight'''), ('''vqa_classifier.3.bias''', '''classifier.3.bias'''), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('''nlvr2_classifier.0.weight''', '''classifier.0.weight'''), ('''nlvr2_classifier.0.bias''', '''classifier.0.bias'''), ('''nlvr2_classifier.1.weight''', '''classifier.1.weight'''), ('''nlvr2_classifier.1.bias''', '''classifier.1.bias'''), ('''nlvr2_classifier.3.weight''', '''classifier.3.weight'''), ('''nlvr2_classifier.3.bias''', '''classifier.3.bias'''), ] ) else: pass return rename_keys def _A (__a , __a ) -> Union[str, Any]: """simple docstring""" for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE_ : List[Any] = '''vilt.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : Tuple = state_dict.pop(f'transformer.blocks.{i}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE_ : Tuple = state_dict.pop(f'transformer.blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : int = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE_ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE_ : Dict = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_bias[-config.hidden_size :] def _A (__a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(__a , __a ) def _A (__a , __a , __a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = dct.pop(__a ) SCREAMING_SNAKE_CASE_ : Any = val @torch.no_grad() def _A (__a , __a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = False SCREAMING_SNAKE_CASE_ : Any = False SCREAMING_SNAKE_CASE_ : Optional[Any] = False SCREAMING_SNAKE_CASE_ : Any = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : Any = 31_29 SCREAMING_SNAKE_CASE_ : List[Any] = '''huggingface/label-files''' SCREAMING_SNAKE_CASE_ : Tuple = '''vqa2-id2label.json''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = json.load(open(hf_hub_download(__a , __a , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE_ : List[str] = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : List[str] = idalabel SCREAMING_SNAKE_CASE_ : Optional[int] = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : List[str] = ViltForQuestionAnswering(__a ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE_ : List[Any] = True SCREAMING_SNAKE_CASE_ : str = 2 SCREAMING_SNAKE_CASE_ : Tuple = {0: '''False''', 1: '''True'''} SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE_ : Any = 3 SCREAMING_SNAKE_CASE_ : Union[str, Any] = ViltForImagesAndTextClassification(__a ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : Dict = ViltForImageAndTextRetrieval(__a ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Optional[Any] = True SCREAMING_SNAKE_CASE_ : Optional[int] = ViltForMaskedLM(__a ) else: raise ValueError('''Unknown model type''' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE_ : Optional[int] = torch.hub.load_state_dict_from_url(__a , map_location='''cpu''' )['''state_dict'''] SCREAMING_SNAKE_CASE_ : Optional[int] = create_rename_keys(__a , __a , __a , __a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) read_in_q_k_v(__a , __a ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE_ : Any = ['''itm_score.fc.weight''', '''itm_score.fc.bias'''] for k in ignore_keys: state_dict.pop(__a , __a ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.load_state_dict(__a , strict=__a ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(__a ) # Define processor SCREAMING_SNAKE_CASE_ : Any = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE_ : int = BertTokenizer.from_pretrained('''bert-base-uncased''' ) SCREAMING_SNAKE_CASE_ : int = ViltProcessor(__a , __a ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE_ : Optional[int] = Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' , stream=__a ).raw ) SCREAMING_SNAKE_CASE_ : Dict = Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' , stream=__a ).raw ) SCREAMING_SNAKE_CASE_ : List[str] = ( '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are''' ''' standing.''' ) SCREAMING_SNAKE_CASE_ : str = processor(__a , __a , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : List[Any] = processor(__a , __a , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : Dict = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg''' , stream=__a ).raw ) if mlm_model: SCREAMING_SNAKE_CASE_ : int = '''a bunch of [MASK] laying on a [MASK].''' else: SCREAMING_SNAKE_CASE_ : Dict = '''How many cats are there?''' SCREAMING_SNAKE_CASE_ : Any = processor(__a , __a , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**__a ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE_ : Any = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.tensor([-12.50_61, -12.51_23, -12.51_74] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , __a , atol=1e-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE_ : str = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE_ : List[Any] = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE_ : str = torch.tensor([-15.94_95, -18.14_72, -10.30_41] ) assert torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , __a , atol=1e-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE_ : Union[str, Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE_ : Tuple = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-2.87_21, 2.12_91] ) assert torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) assert outputs.logits.shape == expected_shape Path(__a ).mkdir(exist_ok=__a ) print(f'Saving model and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) UpperCAmelCase_ : List[str] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
318
"""simple docstring""" from pathlib import Path import numpy as np from PIL import Image def _A (__a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def _A (__a ) -> np.ndarray: """simple docstring""" return (gray > 1_27) & (gray <= 2_55) def _A (__a , __a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = np.zeros_like(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE_ : Union[str, Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE_ : Optional[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE_ : Any = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCAmelCase_ : Dict = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" UpperCAmelCase_ : List[Any] = np.array(Image.open(lena_path)) # kernel to be applied UpperCAmelCase_ : Any = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCAmelCase_ : Tuple = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCAmelCase_ : List[str] = Image.fromarray(output).convert("""RGB""") pil_img.save("""result_dilation.png""")
318
1
"""simple docstring""" from __future__ import annotations import math def _A (__a ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _A (__a ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = str(__a ) SCREAMING_SNAKE_CASE_ : str = [n] for i in range(1 , len(__a ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _A (__a ) -> bool: """simple docstring""" if len(str(__a ) ) > 3: if not is_prime(int(str(__a )[-3:] ) ) or not is_prime(int(str(__a )[:3] ) ): return False return True def _A (__a = 11 ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : list[int] = [] SCREAMING_SNAKE_CASE_ : Optional[Any] = 13 while len(__a ) != count: if validate(__a ): SCREAMING_SNAKE_CASE_ : Tuple = list_truncated_nums(__a ) if all(is_prime(__a ) for i in list_nums ): list_truncated_primes.append(__a ) num += 2 return list_truncated_primes def _A () -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(11)) = }''')
318
"""simple docstring""" from collections import defaultdict def _A (__a , __a ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = first_str.lower().strip() SCREAMING_SNAKE_CASE_ : List[Any] = second_str.lower().strip() # Remove whitespace SCREAMING_SNAKE_CASE_ : Dict = first_str.replace(''' ''' , '''''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = second_str.replace(''' ''' , '''''' ) # Strings of different lengths are not anagrams if len(__a ) != len(__a ): return False # Default values for count should be 0 SCREAMING_SNAKE_CASE_ : defaultdict[str, int] = defaultdict(__a ) # For each character in input strings, # increment count in the corresponding for i in range(len(__a ) ): 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() UpperCAmelCase_ : Any = input("""Enter the first string """).strip() UpperCAmelCase_ : Optional[int] = input("""Enter the second string """).strip() UpperCAmelCase_ : Union[str, Any] = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {'' if status else 'not '}anagrams.''')
318
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : List[str] , lowercase_ : Dict=13 , lowercase_ : Union[str, Any]=7 , lowercase_ : Union[str, Any]=True , lowercase_ : List[str]=True , lowercase_ : Any=True , lowercase_ : Optional[int]=True , lowercase_ : List[str]=99 , lowercase_ : Optional[int]=32 , lowercase_ : List[str]=2 , lowercase_ : Optional[int]=4 , lowercase_ : Tuple=37 , lowercase_ : str="gelu" , lowercase_ : str=0.1 , lowercase_ : Union[str, Any]=0.1 , lowercase_ : Any=512 , lowercase_ : Optional[int]=16 , lowercase_ : Tuple=2 , lowercase_ : str=0.02 , lowercase_ : Union[str, Any]=False , lowercase_ : str=True , lowercase_ : Optional[int]="None" , lowercase_ : Optional[int]=3 , lowercase_ : List[Any]=4 , lowercase_ : List[Any]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE_ : int = seq_length SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_training SCREAMING_SNAKE_CASE_ : List[Any] = use_input_mask SCREAMING_SNAKE_CASE_ : int = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = intermediate_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Any = num_labels SCREAMING_SNAKE_CASE_ : Tuple = num_choices SCREAMING_SNAKE_CASE_ : Tuple = relative_attention SCREAMING_SNAKE_CASE_ : Dict = position_biased_input SCREAMING_SNAKE_CASE_ : List[str] = pos_att_type SCREAMING_SNAKE_CASE_ : Dict = scope def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[str] = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : str = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=lowercase_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : List[Any] , lowercase_ : Dict , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = TFDebertaVaModel(config=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE_ : Tuple = [input_ids, input_mask] SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : List[Any] , lowercase_ : Optional[int] , lowercase_ : Dict , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : int , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = TFDebertaVaForMaskedLM(config=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : int , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Dict , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = TFDebertaVaForSequenceClassification(config=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : Dict = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : int , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : int , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFDebertaVaForTokenClassification(config=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : str = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : Any , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFDebertaVaForQuestionAnswering(config=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : Dict = model(lowercase_) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) __UpperCamelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = TFDebertaVaModelTester(self) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''') self.assertIsNotNone(lowercase_) @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='''Model not available yet''') def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''') SCREAMING_SNAKE_CASE_ : str = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) SCREAMING_SNAKE_CASE_ : List[Any] = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) SCREAMING_SNAKE_CASE_ : Any = model(lowercase_ , attention_mask=lowercase_)[0] SCREAMING_SNAKE_CASE_ : List[Any] = tf.constant( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]]) tf.debugging.assert_near(output[:, 1:4, 1:4] , lowercase_ , atol=1e-4)
318
"""simple docstring""" import argparse from collections import defaultdict import yaml UpperCAmelCase_ : Optional[Any] = """docs/source/en/_toctree.yml""" def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 SCREAMING_SNAKE_CASE_ : List[Any] = [key for key, value in counts.items() if value > 1] SCREAMING_SNAKE_CASE_ : int = [] for duplicate_key in duplicates: SCREAMING_SNAKE_CASE_ : List[str] = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(__a , key=lambda __a : s["title"].lower() ) def _A (__a=False ) -> Tuple: """simple docstring""" with open(__a , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE_ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE_ : str = content[api_idx]['''sections'''] # Then to the model doc SCREAMING_SNAKE_CASE_ : List[Any] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = api_doc[model_idx]['''sections'''] SCREAMING_SNAKE_CASE_ : str = [(idx, section) for idx, section in enumerate(__a ) if '''sections''' in section] SCREAMING_SNAKE_CASE_ : Optional[Any] = False for idx, modality_doc in modalities_docs: SCREAMING_SNAKE_CASE_ : List[str] = modality_doc['''sections'''] SCREAMING_SNAKE_CASE_ : Union[str, Any] = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: SCREAMING_SNAKE_CASE_ : str = True if overwrite: SCREAMING_SNAKE_CASE_ : Optional[int] = new_modality_doc if diff: if overwrite: SCREAMING_SNAKE_CASE_ : List[Any] = model_doc SCREAMING_SNAKE_CASE_ : int = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) 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__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Tuple = parser.parse_args() check_model_doc(args.fix_and_overwrite)
318
1
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = data SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None def _A () -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ : List[Any] = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() SCREAMING_SNAKE_CASE_ : Union[str, Any] = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = q.get() SCREAMING_SNAKE_CASE_ : List[str] = f'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : Optional[int] = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : List[str] = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ : str = f'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : str = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : Any = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : int = right_node q.put(__a ) raise def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Tuple = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : str = [] while not q.empty(): SCREAMING_SNAKE_CASE_ : List[str] = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ : Tuple = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ : str = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Any = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.left SCREAMING_SNAKE_CASE_ : Any = stack.pop() print(n.data , end=''',''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = [], [] SCREAMING_SNAKE_CASE_ : List[Any] = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ : List[str] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def _A (__a = "" , __a=50 , __a="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = divmod(width - len(__a ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase_ : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
318
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
1
"""simple docstring""" from math import pow, sqrt def _A (*__a ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = len(__a ) > 0 and all(value > 0.0 for value in values ) return result def _A (__a , __a ) -> float | ValueError: """simple docstring""" return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__a , __a ) else ValueError('''Input Error: Molar mass values must greater than 0.''' ) ) def _A (__a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__a , __a , __a ) else ValueError( '''Input Error: Molar mass and effusion rate values must greater than 0.''' ) ) def _A (__a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__a , __a , __a ) else ValueError( '''Input Error: Molar mass and effusion rate values must greater than 0.''' ) ) def _A (__a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(__a , __a , __a ) else ValueError( '''Input Error: Molar mass and effusion rate values must greater than 0.''' ) ) def _A (__a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(__a , __a , __a ) else ValueError( '''Input Error: Molar mass and effusion rate values must greater than 0.''' ) )
318
"""simple docstring""" from __future__ import annotations UpperCAmelCase_ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase_ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase_ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _A (__a , __a , __a , __a ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _A (__a ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _A (__a ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__a ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__a , __a , __a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = digit if sudoku(__a ) is not None: return grid SCREAMING_SNAKE_CASE_ : Any = 0 return None def _A (__a ) -> None: """simple docstring""" for row in grid: for cell in row: print(__a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") UpperCAmelCase_ : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
318
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = StableDiffusionInpaintPipeline __UpperCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __UpperCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __UpperCamelCase = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCamelCase = frozenset([] ) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = PNDMScheduler(skip_prk_steps=lowercase_) torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) SCREAMING_SNAKE_CASE_ : int = CLIPTextModel(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') SCREAMING_SNAKE_CASE_ : int = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : str=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase_)).to(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE_ : Optional[int] = Image.fromarray(np.uinta(lowercase_)).convert('''RGB''').resize((64, 64)) SCREAMING_SNAKE_CASE_ : Dict = Image.fromarray(np.uinta(image + 4)).convert('''RGB''').resize((64, 64)) if str(lowercase_).startswith('''mps'''): SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = torch.Generator(device=lowercase_).manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : str = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_ : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = StableDiffusionInpaintPipeline(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = sd_pipe.to(lowercase_) sd_pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_dummy_inputs(lowercase_) SCREAMING_SNAKE_CASE_ : int = sd_pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array([0.47_27, 0.57_35, 0.39_41, 0.54_46, 0.59_26, 0.43_94, 0.50_62, 0.46_54, 0.44_76]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''') SCREAMING_SNAKE_CASE_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''') SCREAMING_SNAKE_CASE_ : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''stabilityai/stable-diffusion-2-inpainting''' SCREAMING_SNAKE_CASE_ : Dict = StableDiffusionInpaintPipeline.from_pretrained(lowercase_ , safety_checker=lowercase_) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_ : Optional[int] = '''Face of a yellow cat, high resolution, sitting on a park bench''' SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe( prompt=lowercase_ , image=lowercase_ , mask_image=lowercase_ , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 9e-3 def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''') SCREAMING_SNAKE_CASE_ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''') SCREAMING_SNAKE_CASE_ : Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''') SCREAMING_SNAKE_CASE_ : int = '''stabilityai/stable-diffusion-2-inpainting''' SCREAMING_SNAKE_CASE_ : Optional[Any] = StableDiffusionInpaintPipeline.from_pretrained( lowercase_ , torch_dtype=torch.floataa , safety_checker=lowercase_ , ) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE_ : Dict = '''Face of a yellow cat, high resolution, sitting on a park bench''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[str] = pipe( prompt=lowercase_ , image=lowercase_ , mask_image=lowercase_ , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : str = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 5e-1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE_ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''') SCREAMING_SNAKE_CASE_ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''') SCREAMING_SNAKE_CASE_ : Dict = '''stabilityai/stable-diffusion-2-inpainting''' SCREAMING_SNAKE_CASE_ : List[Any] = PNDMScheduler.from_pretrained(lowercase_ , subfolder='''scheduler''') SCREAMING_SNAKE_CASE_ : List[str] = StableDiffusionInpaintPipeline.from_pretrained( lowercase_ , safety_checker=lowercase_ , scheduler=lowercase_ , torch_dtype=torch.floataa , ) pipe.to(lowercase_) pipe.set_progress_bar_config(disable=lowercase_) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : List[Any] = '''Face of a yellow cat, high resolution, sitting on a park bench''' SCREAMING_SNAKE_CASE_ : Optional[int] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=lowercase_ , image=lowercase_ , mask_image=lowercase_ , generator=lowercase_ , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
318
"""simple docstring""" from itertools import permutations def _A (__a ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAKE_CASE_ : List[str] = [7, 11, 13, 17] for i, test in enumerate(__a ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _A (__a = 10 ) -> int: """simple docstring""" return sum( int(''''''.join(map(__a , __a ) ) ) for num in permutations(range(__a ) ) if is_substring_divisible(__a ) ) if __name__ == "__main__": print(f'''{solution() = }''')
318
1
"""simple docstring""" import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class lowerCAmelCase__ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any , lowercase_ : Dict[str, int] , lowercase_ : List[str] , lowercase_ : int = None , lowercase_ : int = None): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : str = pad_token_id SCREAMING_SNAKE_CASE_ : Optional[int] = max_length SCREAMING_SNAKE_CASE_ : Dict = vocab SCREAMING_SNAKE_CASE_ : Dict = merges SCREAMING_SNAKE_CASE_ : Union[str, Any] = BytePairTokenizer(lowercase_ , lowercase_ , sequence_length=lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : GPTaTokenizer , *lowercase_ : Optional[Any] , **lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = [''' '''.join(lowercase_) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE_ : str = tokenizer.get_vocab() return cls(lowercase_ , lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowercase_ : Union[str, os.PathLike] , *lowercase_ : List[str] , **lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = GPTaTokenizer.from_pretrained(lowercase_ , *lowercase_ , **lowercase_) return cls.from_tokenizer(lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : List[Any]): '''simple docstring''' return cls(**lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[Any] , lowercase_ : int = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.tf_tokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.ones_like(lowercase_) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = pad_model_inputs( lowercase_ , max_seq_length=lowercase_ , pad_value=self.pad_token_id) return {"attention_mask": attention_mask, "input_ids": input_ids}
318
"""simple docstring""" UpperCAmelCase_ : List[Any] = 9.8_0_6_6_5 def _A (__a , __a , __a = g ) -> float: """simple docstring""" if fluid_density <= 0: raise ValueError('''Impossible fluid density''' ) if volume < 0: raise ValueError('''Impossible Object volume''' ) if gravity <= 0: raise ValueError('''Impossible Gravity''' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
318
1
"""simple docstring""" import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : int , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = jnp.ones((batch_size, length)) / length return scores def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : List[str] = 20 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._get_uniform_logits(batch_size=2 , length=lowercase_) # tweak scores to not be uniform anymore SCREAMING_SNAKE_CASE_ : Tuple = scores.at[1, 5].set((1 / length) + 0.1) # peak, 1st batch SCREAMING_SNAKE_CASE_ : str = scores.at[1, 10].set((1 / length) - 0.4) # valley, 1st batch # compute softmax SCREAMING_SNAKE_CASE_ : int = jax.nn.softmax(lowercase_ , axis=-1) SCREAMING_SNAKE_CASE_ : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=0.5) SCREAMING_SNAKE_CASE_ : Dict = FlaxTemperatureLogitsWarper(temperature=1.3) SCREAMING_SNAKE_CASE_ : Optional[int] = jax.nn.softmax(temp_dist_warper_sharper(lowercase_ , scores.copy() , cur_len=lowercase_) , axis=-1) SCREAMING_SNAKE_CASE_ : List[Any] = jax.nn.softmax(temp_dist_warper_smoother(lowercase_ , scores.copy() , cur_len=lowercase_) , axis=-1) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3)) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3)) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max()) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min()) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max()) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min()) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Optional[int] = 10 SCREAMING_SNAKE_CASE_ : Any = 2 # create ramp distribution SCREAMING_SNAKE_CASE_ : Optional[Any] = np.broadcast_to(np.arange(lowercase_)[None, :] , (batch_size, vocab_size)).copy() SCREAMING_SNAKE_CASE_ : Optional[int] = ramp_logits[1:, : vocab_size // 2] + vocab_size SCREAMING_SNAKE_CASE_ : int = FlaxTopKLogitsWarper(3) SCREAMING_SNAKE_CASE_ : Optional[int] = top_k_warp(lowercase_ , lowercase_ , cur_len=lowercase_) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0]).tolist() , 7 * [True] + 3 * [False]) self.assertListEqual(jnp.isinf(scores[1]).tolist() , 2 * [True] + 3 * [False] + 5 * [True]) # check special case SCREAMING_SNAKE_CASE_ : Optional[int] = 5 SCREAMING_SNAKE_CASE_ : str = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3) SCREAMING_SNAKE_CASE_ : List[str] = np.broadcast_to(np.arange(lowercase_)[None, :] , (batch_size, length)).copy() SCREAMING_SNAKE_CASE_ : Tuple = top_k_warp_safety_check(lowercase_ , lowercase_ , cur_len=lowercase_) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1).tolist() , [2, 2]) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : int = 10 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) SCREAMING_SNAKE_CASE_ : List[str] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]])) SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxTopPLogitsWarper(0.8) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.exp(top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_)) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-3)) # check edge cases with negative and extreme logits SCREAMING_SNAKE_CASE_ : List[str] = np.broadcast_to(np.arange(lowercase_)[None, :] , (batch_size, vocab_size)).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme SCREAMING_SNAKE_CASE_ : Optional[int] = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept SCREAMING_SNAKE_CASE_ : str = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0) SCREAMING_SNAKE_CASE_ : int = top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1).tolist() , [3, 2]) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = 20 SCREAMING_SNAKE_CASE_ : Optional[Any] = 4 SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase_) # check that min length is applied at length 5 SCREAMING_SNAKE_CASE_ : str = ids_tensor((batch_size, 20) , vocab_size=20) SCREAMING_SNAKE_CASE_ : Any = 5 SCREAMING_SNAKE_CASE_ : List[Any] = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = min_dist_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''')]) # check that min length is not applied anymore at length 15 SCREAMING_SNAKE_CASE_ : int = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = 15 SCREAMING_SNAKE_CASE_ : Union[str, Any] = min_dist_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertFalse(jnp.isinf(lowercase_).any()) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = 20 SCREAMING_SNAKE_CASE_ : Optional[int] = 4 SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase_) # check that all scores are -inf except the bos_token_id score SCREAMING_SNAKE_CASE_ : Any = ids_tensor((batch_size, 1) , vocab_size=20) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : List[Any] = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]).all()) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0]) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Any = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertFalse(jnp.isinf(lowercase_).any()) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = 20 SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 5 SCREAMING_SNAKE_CASE_ : Dict = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase_ , eos_token_id=lowercase_) # check that all scores are -inf except the eos_token_id when max_length is reached SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor((batch_size, 4) , vocab_size=20) SCREAMING_SNAKE_CASE_ : Optional[Any] = 4 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]).all()) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0]) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached SCREAMING_SNAKE_CASE_ : Optional[int] = 3 SCREAMING_SNAKE_CASE_ : Any = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = logits_processor(lowercase_ , lowercase_ , cur_len=lowercase_) self.assertFalse(jnp.isinf(lowercase_).any()) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = 4 SCREAMING_SNAKE_CASE_ : Optional[Any] = 10 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 15 SCREAMING_SNAKE_CASE_ : Optional[int] = 2 SCREAMING_SNAKE_CASE_ : Optional[int] = 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor((batch_size, sequence_length) , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = input_ids.copy() SCREAMING_SNAKE_CASE_ : Dict = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ : Dict = FlaxTemperatureLogitsWarper(temperature=0.5) SCREAMING_SNAKE_CASE_ : List[str] = FlaxTopKLogitsWarper(3) SCREAMING_SNAKE_CASE_ : List[Any] = FlaxTopPLogitsWarper(0.8) # instantiate all logits processors SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : Any = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase_ , eos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 10 # no processor list SCREAMING_SNAKE_CASE_ : Tuple = temp_dist_warp(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = top_k_warp(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : int = min_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : Any = bos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : str = eos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) # with processor list SCREAMING_SNAKE_CASE_ : List[str] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]) SCREAMING_SNAKE_CASE_ : Dict = processor(lowercase_ , lowercase_ , cur_len=lowercase_) # scores should be equal self.assertTrue(jnp.allclose(lowercase_ , lowercase_ , atol=1e-3)) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist()) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = 4 SCREAMING_SNAKE_CASE_ : int = 10 SCREAMING_SNAKE_CASE_ : List[Any] = 15 SCREAMING_SNAKE_CASE_ : str = 2 SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor((batch_size, sequence_length) , lowercase_) SCREAMING_SNAKE_CASE_ : int = input_ids.copy() SCREAMING_SNAKE_CASE_ : str = self._get_uniform_logits(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ : str = FlaxTemperatureLogitsWarper(temperature=0.5) SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxTopKLogitsWarper(3) SCREAMING_SNAKE_CASE_ : List[str] = FlaxTopPLogitsWarper(0.8) # instantiate all logits processors SCREAMING_SNAKE_CASE_ : List[str] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : int = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : str = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase_ , eos_token_id=lowercase_) SCREAMING_SNAKE_CASE_ : str = 10 # no processor list def run_no_processor_list(lowercase_ : str , lowercase_ : Tuple , lowercase_ : str): SCREAMING_SNAKE_CASE_ : Tuple = temp_dist_warp(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : int = top_k_warp(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = top_p_warp(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = min_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = bos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = eos_dist_proc(lowercase_ , lowercase_ , cur_len=lowercase_) return scores # with processor list def run_processor_list(lowercase_ : Optional[int] , lowercase_ : List[Any] , lowercase_ : Any): SCREAMING_SNAKE_CASE_ : int = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]) SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor(lowercase_ , lowercase_ , cur_len=lowercase_) return scores SCREAMING_SNAKE_CASE_ : List[str] = jax.jit(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.jit(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = jitted_run_no_processor_list(lowercase_ , lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = jitted_run_processor_list(lowercase_ , lowercase_ , lowercase_) # scores should be equal self.assertTrue(jnp.allclose(lowercase_ , lowercase_ , atol=1e-3)) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist())
318
"""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. UpperCAmelCase_ : Union[str, Any] = abspath(join(dirname(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 _A (__a ) -> Union[str, Any]: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def _A (__a ) -> Any: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE_ : Optional[Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a , id=__a )
318
1
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets UpperCAmelCase_ : List[str] = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ UpperCAmelCase_ : Optional[Any] = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ UpperCAmelCase_ : str = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def _A (__a ) -> int: """simple docstring""" def remove_articles(__a ): SCREAMING_SNAKE_CASE_ : Tuple = re.compile(R'''\b(a|an|the)\b''' , re.UNICODE ) return re.sub(__a , ''' ''' , __a ) def white_space_fix(__a ): return " ".join(text.split() ) def remove_punc(__a ): SCREAMING_SNAKE_CASE_ : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__a ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__a ) ) ) ) def _A (__a , __a ) -> Optional[int]: """simple docstring""" return int(normalize_answer(__a ) == normalize_answer(__a ) ) def _A (__a , __a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [any(compute_exact(__a , __a ) for ref in refs ) for pred, refs in zip(__a , __a )] return (sum(__a ) / len(__a )) * 1_00 def _A (__a , __a , __a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [rgram for rgrams in rgramslist for rgram in rgrams] SCREAMING_SNAKE_CASE_ : List[str] = Counter(__a ) SCREAMING_SNAKE_CASE_ : Tuple = Counter(__a ) SCREAMING_SNAKE_CASE_ : Dict = Counter() for sgram, scount in sgramcounter.items(): SCREAMING_SNAKE_CASE_ : Any = scount * numref SCREAMING_SNAKE_CASE_ : Optional[int] = Counter(__a ) SCREAMING_SNAKE_CASE_ : int = Counter() for cgram, ccount in cgramcounter.items(): SCREAMING_SNAKE_CASE_ : int = ccount * numref # KEEP SCREAMING_SNAKE_CASE_ : Union[str, Any] = sgramcounter_rep & cgramcounter_rep SCREAMING_SNAKE_CASE_ : Any = keepgramcounter_rep & rgramcounter SCREAMING_SNAKE_CASE_ : Optional[int] = sgramcounter_rep & rgramcounter SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : Optional[int] = 1 if len(__a ) > 0: SCREAMING_SNAKE_CASE_ : Optional[int] = keeptmpscorea / len(__a ) if len(__a ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) SCREAMING_SNAKE_CASE_ : str = keeptmpscorea / sum(keepgramcounterall_rep.values() ) SCREAMING_SNAKE_CASE_ : Tuple = 0 if keepscore_precision > 0 or keepscore_recall > 0: SCREAMING_SNAKE_CASE_ : int = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION SCREAMING_SNAKE_CASE_ : Optional[Any] = sgramcounter_rep - cgramcounter_rep SCREAMING_SNAKE_CASE_ : str = delgramcounter_rep - rgramcounter SCREAMING_SNAKE_CASE_ : int = sgramcounter_rep - rgramcounter SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : int = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. SCREAMING_SNAKE_CASE_ : Any = 1 if len(__a ) > 0: SCREAMING_SNAKE_CASE_ : Dict = deltmpscorea / len(__a ) # ADDITION SCREAMING_SNAKE_CASE_ : str = set(__a ) - set(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = set(__a ) & set(__a ) SCREAMING_SNAKE_CASE_ : Dict = set(__a ) - set(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. SCREAMING_SNAKE_CASE_ : Any = 1 SCREAMING_SNAKE_CASE_ : int = 1 if len(__a ) > 0: SCREAMING_SNAKE_CASE_ : List[str] = addtmpscore / len(__a ) if len(__a ) > 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = addtmpscore / len(__a ) SCREAMING_SNAKE_CASE_ : str = 0 if addscore_precision > 0 or addscore_recall > 0: SCREAMING_SNAKE_CASE_ : Tuple = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def _A (__a , __a , __a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = len(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = ssent.split(''' ''' ) SCREAMING_SNAKE_CASE_ : int = csent.split(''' ''' ) SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = [] SCREAMING_SNAKE_CASE_ : Tuple = [] for rsent in rsents: SCREAMING_SNAKE_CASE_ : Any = rsent.split(''' ''' ) SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : str = [] ragramslist.append(__a ) for i in range(0 , len(__a ) - 1 ): if i < len(__a ) - 1: SCREAMING_SNAKE_CASE_ : Any = ragrams[i] + ''' ''' + ragrams[i + 1] ragrams.append(__a ) if i < len(__a ) - 2: SCREAMING_SNAKE_CASE_ : Optional[int] = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] ragrams.append(__a ) if i < len(__a ) - 3: SCREAMING_SNAKE_CASE_ : Tuple = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] + ''' ''' + ragrams[i + 3] ragrams.append(__a ) ragramslist.append(__a ) ragramslist.append(__a ) ragramslist.append(__a ) for i in range(0 , len(__a ) - 1 ): if i < len(__a ) - 1: SCREAMING_SNAKE_CASE_ : Optional[int] = sagrams[i] + ''' ''' + sagrams[i + 1] sagrams.append(__a ) if i < len(__a ) - 2: SCREAMING_SNAKE_CASE_ : List[Any] = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] sagrams.append(__a ) if i < len(__a ) - 3: SCREAMING_SNAKE_CASE_ : Optional[Any] = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] + ''' ''' + sagrams[i + 3] sagrams.append(__a ) for i in range(0 , len(__a ) - 1 ): if i < len(__a ) - 1: SCREAMING_SNAKE_CASE_ : Dict = cagrams[i] + ''' ''' + cagrams[i + 1] cagrams.append(__a ) if i < len(__a ) - 2: SCREAMING_SNAKE_CASE_ : Optional[int] = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] cagrams.append(__a ) if i < len(__a ) - 3: SCREAMING_SNAKE_CASE_ : List[str] = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] + ''' ''' + cagrams[i + 3] cagrams.append(__a ) ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : Any = SARIngram(__a , __a , __a , __a ) ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : List[Any] = SARIngram(__a , __a , __a , __a ) ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : List[Any] = SARIngram(__a , __a , __a , __a ) ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : List[Any] = SARIngram(__a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : Dict = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 SCREAMING_SNAKE_CASE_ : Tuple = sum([delascore, delascore, delascore, delascore] ) / 4 SCREAMING_SNAKE_CASE_ : Optional[int] = sum([addascore, addascore, addascore, addascore] ) / 4 SCREAMING_SNAKE_CASE_ : Optional[int] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def _A (__a , __a = True , __a = "13a" , __a = True ) -> str: """simple docstring""" if lowercase: SCREAMING_SNAKE_CASE_ : Tuple = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: SCREAMING_SNAKE_CASE_ : Any = sacrebleu.metrics.bleu._get_tokenizer(__a )()(__a ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = sacrebleu.TOKENIZERS[tokenizer]()(__a ) elif tokenizer == "moses": SCREAMING_SNAKE_CASE_ : Tuple = sacremoses.MosesTokenizer().tokenize(__a , return_str=__a , escape=__a ) elif tokenizer == "penn": SCREAMING_SNAKE_CASE_ : int = sacremoses.MosesTokenizer().penn_tokenize(__a , return_str=__a ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = sentence if not return_str: SCREAMING_SNAKE_CASE_ : Dict = normalized_sent.split() return normalized_sent def _A (__a , __a , __a ) -> Optional[Any]: """simple docstring""" if not (len(__a ) == len(__a ) == len(__a )): raise ValueError('''Sources length must match predictions and references lengths.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = 0 for src, pred, refs in zip(__a , __a , __a ): sari_score += SARIsent(normalize(__a ) , normalize(__a ) , [normalize(__a ) for sent in refs] ) SCREAMING_SNAKE_CASE_ : Dict = sari_score / len(__a ) return 1_00 * sari_score def _A (__a , __a , __a="exp" , __a=None , __a=False , __a=False , __a=False , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = len(references[0] ) if any(len(__a ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [[refs[i] for refs in references] for i in range(__a )] SCREAMING_SNAKE_CASE_ : Any = sacrebleu.corpus_bleu( __a , __a , smooth_method=__a , smooth_value=__a , force=__a , lowercase=__a , use_effective_order=__a , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence'''), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''') , id='''references'''), }) , codebase_urls=[ '''https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py''', '''https://github.com/cocoxu/simplification/blob/master/SARI.py''', '''https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py''', '''https://github.com/mjpost/sacreBLEU''', ] , reference_urls=[ '''https://www.aclweb.org/anthology/Q16-1029.pdf''', '''https://github.com/mjpost/sacreBLEU''', '''https://en.wikipedia.org/wiki/BLEU''', '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Any , lowercase_ : List[Any] , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = {} result.update({'''sari''': compute_sari(sources=lowercase_ , predictions=lowercase_ , references=lowercase_)}) result.update({'''sacrebleu''': compute_sacrebleu(predictions=lowercase_ , references=lowercase_)}) result.update({'''exact''': compute_em(predictions=lowercase_ , references=lowercase_)}) return result
318
"""simple docstring""" import argparse import os import re import packaging.version UpperCAmelCase_ : Any = """examples/""" UpperCAmelCase_ : Optional[int] = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCAmelCase_ : List[Any] = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCAmelCase_ : Optional[int] = """README.md""" def _A (__a , __a , __a ) -> int: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Optional[Any] = f.read() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = REPLACE_PATTERNS[pattern] SCREAMING_SNAKE_CASE_ : Optional[int] = replace.replace('''VERSION''' , __a ) SCREAMING_SNAKE_CASE_ : Tuple = re_pattern.sub(__a , __a ) with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(__a ) def _A (__a ) -> int: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a , __a ) , __a , pattern='''examples''' ) def _A (__a , __a=False ) -> List[str]: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a , __a , __a ) if not patch: update_version_in_examples(__a ) def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' SCREAMING_SNAKE_CASE_ : Optional[int] = '''1. Want to contribute a new model?''' with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Tuple = f.readlines() # Find the start of the list. SCREAMING_SNAKE_CASE_ : Tuple = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Dict = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): SCREAMING_SNAKE_CASE_ : List[Any] = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__a ) def _A () -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] , '''r''' ) as f: SCREAMING_SNAKE_CASE_ : Any = f.read() SCREAMING_SNAKE_CASE_ : Dict = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def _A (__a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: SCREAMING_SNAKE_CASE_ : List[Any] = default_version.base_version elif patch: SCREAMING_SNAKE_CASE_ : int = f'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: SCREAMING_SNAKE_CASE_ : Any = f'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are you releasing? [{default_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = default_version print(f'Updating version to {version}.' ) global_version_update(__a , patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def _A () -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_version() SCREAMING_SNAKE_CASE_ : Any = f'{current_version.major}.{current_version.minor + 1}.0.dev0' SCREAMING_SNAKE_CASE_ : Union[str, Any] = current_version.base_version # Check with the user we got that right. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are we developing now? [{dev_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[int] = dev_version print(f'Updating version to {version}.' ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCAmelCase_ : int = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
318
1
"""simple docstring""" import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = {"""vocab_file""": """spiece.model"""} UpperCAmelCase_ : List[str] = { """vocab_file""": { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""", """google/bigbird-roberta-large""": ( """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model""" ), """google/bigbird-base-trivia-itc""": ( """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model""" ), } } UpperCAmelCase_ : int = { """google/bigbird-roberta-base""": 4096, """google/bigbird-roberta-large""": 4096, """google/bigbird-base-trivia-itc""": 4096, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = [] def __init__( self : Optional[int] , lowercase_ : str , lowercase_ : List[str]="<unk>" , lowercase_ : Any="<s>" , lowercase_ : Any="</s>" , lowercase_ : Tuple="<pad>" , lowercase_ : Dict="[SEP]" , lowercase_ : int="[MASK]" , lowercase_ : Dict="[CLS]" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else bos_token SCREAMING_SNAKE_CASE_ : List[Any] = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else eos_token SCREAMING_SNAKE_CASE_ : Tuple = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else unk_token SCREAMING_SNAKE_CASE_ : Optional[int] = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else pad_token SCREAMING_SNAKE_CASE_ : Tuple = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else cls_token SCREAMING_SNAKE_CASE_ : Tuple = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE_ : Union[str, Any] = AddedToken(lowercase_ , lstrip=lowercase_ , rstrip=lowercase_) if isinstance(lowercase_ , lowercase_) else mask_token SCREAMING_SNAKE_CASE_ : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , pad_token=lowercase_ , sep_token=lowercase_ , mask_token=lowercase_ , cls_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_file SCREAMING_SNAKE_CASE_ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(lowercase_) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Tuple = None return state def __setstate__( self : Dict , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Any = {} SCREAMING_SNAKE_CASE_ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Optional[int]): '''simple docstring''' return self.sp_model.piece_to_id(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.IdToPiece(lowercase_) return token def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase_) + token SCREAMING_SNAKE_CASE_ : Optional[Any] = True SCREAMING_SNAKE_CASE_ : str = [] else: current_sub_tokens.append(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = False out_string += self.sp_model.decode(lowercase_) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : List[int] , lowercase_ : bool = False , lowercase_ : bool = None , lowercase_ : bool = True , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''use_source_tokenizer''' , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.convert_ids_to_tokens(lowercase_ , skip_special_tokens=lowercase_) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : Optional[int] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(lowercase_)) SCREAMING_SNAKE_CASE_ : Dict = [] sub_texts.append(lowercase_) else: current_sub_text.append(lowercase_) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(lowercase_)) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: SCREAMING_SNAKE_CASE_ : Optional[int] = re.sub(r''' (\[(MASK|SEP)\])''' , r'''\1''' , ''' '''.join(lowercase_)) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ''''''.join(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.clean_up_tokenization(lowercase_) return clean_text else: return text def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : str = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : Tuple = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE_ : str = [self.cls_token_id] SCREAMING_SNAKE_CASE_ : Any = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) + [1] return [1] + ([0] * len(lowercase_)) + [1] + ([0] * len(lowercase_)) + [1] def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]
318
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _A (__a , __a , __a=1e-12 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T SCREAMING_SNAKE_CASE_ : List[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T return jnp.matmul(__a , norm_emb_a.T ) class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxCLIPVisionModule(self.config.vision_config) SCREAMING_SNAKE_CASE_ : Tuple = nn.Dense(self.config.projection_dim , use_bias=lowercase_ , dtype=self.dtype) SCREAMING_SNAKE_CASE_ : List[str] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Dict = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,)) def __call__( self : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.vision_model(lowercase_)[1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.visual_projection(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.special_care_embeds) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs SCREAMING_SNAKE_CASE_ : Tuple = 0.0 SCREAMING_SNAKE_CASE_ : Dict = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment SCREAMING_SNAKE_CASE_ : Optional[int] = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : List[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=lowercase_) # Use a lower threshold if an image has any special care concept SCREAMING_SNAKE_CASE_ : Dict = is_special_care * 0.01 SCREAMING_SNAKE_CASE_ : str = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment SCREAMING_SNAKE_CASE_ : Any = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : Dict = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = CLIPConfig __UpperCamelCase = "clip_input" __UpperCamelCase = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Union[str, Any] , lowercase_ : CLIPConfig , lowercase_ : Optional[Tuple] = None , lowercase_ : int = 0 , lowercase_ : jnp.dtype = jnp.floataa , lowercase_ : bool = True , **lowercase_ : Any , ): '''simple docstring''' if input_shape is None: SCREAMING_SNAKE_CASE_ : List[str] = (1, 224, 224, 3) SCREAMING_SNAKE_CASE_ : List[Any] = self.module_class(config=lowercase_ , dtype=lowercase_ , **lowercase_) super().__init__(lowercase_ , lowercase_ , input_shape=lowercase_ , seed=lowercase_ , dtype=lowercase_ , _do_init=_do_init) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : jax.random.KeyArray , lowercase_ : Tuple , lowercase_ : FrozenDict = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = jax.random.normal(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = jax.random.split(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = {'''params''': params_rng, '''dropout''': dropout_rng} SCREAMING_SNAKE_CASE_ : List[Any] = self.module.init(lowercase_ , lowercase_)['''params'''] return random_params def __call__( self : List[Any] , lowercase_ : List[str] , lowercase_ : dict = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = jnp.transpose(lowercase_ , (0, 2, 3, 1)) return self.module.apply( {'''params''': params or self.params} , jnp.array(lowercase_ , dtype=jnp.floataa) , rngs={} , )
318
1
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def _A (__a , __a , __a , __a , __a , __a = None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = {} if train_file is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = [train_file] if eval_file is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = [eval_file] if test_file is not None: SCREAMING_SNAKE_CASE_ : Dict = [test_file] SCREAMING_SNAKE_CASE_ : List[Any] = datasets.load_dataset('''csv''' , data_files=__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(ds[list(files.keys() )[0]].features.keys() ) SCREAMING_SNAKE_CASE_ : int = features_name.pop(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(set(ds[list(files.keys() )[0]][label_name] ) ) SCREAMING_SNAKE_CASE_ : List[Any] = {label: i for i, label in enumerate(__a )} SCREAMING_SNAKE_CASE_ : Dict = tokenizer.model_input_names SCREAMING_SNAKE_CASE_ : Any = {} if len(__a ) == 1: for k in files.keys(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = ds[k].map( lambda __a : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=__a , max_length=__a , padding='''max_length''' ) , batched=__a , ) elif len(__a ) == 2: for k in files.keys(): SCREAMING_SNAKE_CASE_ : Dict = ds[k].map( lambda __a : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=__a , max_length=__a , padding='''max_length''' , ) , batched=__a , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = {k: v for k, v in ex.items() if k in input_names} SCREAMING_SNAKE_CASE_ : Union[str, Any] = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: SCREAMING_SNAKE_CASE_ : Optional[Any] = {k: v for k, v in ex.items() if k in input_names} SCREAMING_SNAKE_CASE_ : Any = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: SCREAMING_SNAKE_CASE_ : Any = {k: v for k, v in ex.items() if k in input_names} SCREAMING_SNAKE_CASE_ : Any = labelaid[ex[label_name]] yield (d, label) SCREAMING_SNAKE_CASE_ : Any = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: SCREAMING_SNAKE_CASE_ : List[Any] = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) SCREAMING_SNAKE_CASE_ : List[str] = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: SCREAMING_SNAKE_CASE_ : int = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) SCREAMING_SNAKE_CASE_ : int = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid UpperCAmelCase_ : Any = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = field(metadata={"help": "Which column contains the label"} ) __UpperCamelCase = field(default=UpperCAmelCase__ , metadata={"help": "The path of the training file"} ) __UpperCamelCase = field(default=UpperCAmelCase__ , metadata={"help": "The path of the development file"} ) __UpperCamelCase = field(default=UpperCAmelCase__ , metadata={"help": "The path of the test file"} ) __UpperCamelCase = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) @dataclass class lowerCAmelCase__ : '''simple docstring''' __UpperCamelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase = field(default=UpperCAmelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __UpperCamelCase = field( default=UpperCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info( f'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ' f'16-bits training: {training_args.fpaa}' ) logger.info(f'Training/evaluation parameters {training_args}' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=__a , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(__a ) , labelaid=__a , idalabel={id: label for label, id in labelaid.items()} , finetuning_task='''text-classification''' , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): SCREAMING_SNAKE_CASE_ : Optional[Any] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool('''.bin''' in model_args.model_name_or_path ) , config=__a , cache_dir=model_args.cache_dir , ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ : Any = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer SCREAMING_SNAKE_CASE_ : Optional[Any] = TFTrainer( model=__a , args=__a , train_dataset=__a , eval_dataset=__a , compute_metrics=__a , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ : Optional[Any] = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ : Dict = trainer.evaluate() SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join(training_args.output_dir , '''eval_results.txt''' ) with open(__a , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) results.update(__a ) return results if __name__ == "__main__": main()
318
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = data SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None def _A () -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ : List[Any] = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() SCREAMING_SNAKE_CASE_ : Union[str, Any] = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = q.get() SCREAMING_SNAKE_CASE_ : List[str] = f'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : Optional[int] = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : List[str] = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ : str = f'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : str = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : Any = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : int = right_node q.put(__a ) raise def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Tuple = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : str = [] while not q.empty(): SCREAMING_SNAKE_CASE_ : List[str] = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ : Tuple = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ : str = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Any = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.left SCREAMING_SNAKE_CASE_ : Any = stack.pop() print(n.data , end=''',''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = [], [] SCREAMING_SNAKE_CASE_ : List[Any] = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ : List[str] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def _A (__a = "" , __a=50 , __a="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = divmod(width - len(__a ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase_ : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
318
1
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ : Tuple = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = XLMProphetNetTokenizer __UpperCamelCase = False __UpperCamelCase = True def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_ : str = XLMProphetNetTokenizer(lowercase_ , keep_accents=lowercase_) tokenizer.save_pretrained(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''[PAD]''' SCREAMING_SNAKE_CASE_ : str = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_) , lowercase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_) , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''[PAD]''') self.assertEqual(vocab_keys[1] , '''[CLS]''') self.assertEqual(vocab_keys[-1] , '''j''') self.assertEqual(len(lowercase_) , 1012) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1012) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = XLMProphetNetTokenizer(lowercase_ , keep_accents=lowercase_) SCREAMING_SNAKE_CASE_ : Any = tokenizer.tokenize('''This is a test''') self.assertListEqual(lowercase_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE_ : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer.convert_tokens_to_ids(lowercase_) self.assertListEqual( lowercase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.convert_ids_to_tokens(lowercase_) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''[UNK]''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''[UNK]''', '''.''', ] , ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''') @slow def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = '''Hello World!''' SCREAMING_SNAKE_CASE_ : int = [35389, 6672, 49, 2] self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_)) @slow def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = {'''input_ids''': [[11073, 82783, 18, 26, 82783, 549, 51540, 248, 17209, 1301, 217, 20, 215186, 1325, 147, 17209, 1301, 217, 20, 56370, 53, 122020, 20, 16477, 27, 87355, 4548, 20, 4728, 78392, 17, 159969, 18, 26, 24491, 629, 15, 538, 22704, 5439, 15, 2788, 24491, 9885, 15, 43534, 605, 15, 814, 18403, 33200, 29, 15, 43534, 24458, 12410, 111, 24966, 83669, 9637, 144068, 26, 850, 22346, 27, 147, 24966, 83669, 83490, 26, 39113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 122020, 115785, 34, 816, 1339, 46887, 18, 147, 53905, 1951, 42238, 41170, 17732, 834, 436, 15, 27523, 98733, 217, 147, 5542, 4981, 930, 17347, 16, 2], [20091, 629, 94, 82786, 58, 490, 20, 1528, 84, 53905, 344, 80592, 110128, 18822, 5267, 1306, 62, 152537, 308, 7997, 401, 124427, 549, 35442, 225, 109, 15055, 25748, 147, 7119, 43712, 34, 767, 135366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63784, 119466, 17, 147808, 88214, 18, 656, 81, 32, 3296, 10280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='''microsoft/xprophetnet-large-wiki100-cased''' , revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''' , )
318
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = "ssube/stable-diffusion-x4-upscaler-onnx" def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any]=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, 3, 128, 128) , rng=random.Random(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Dict = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Tuple = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array( [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : List[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : int = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[int] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array( [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ort.SessionOptions() SCREAMING_SNAKE_CASE_ : Optional[int] = False return options def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Optional[int] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) SCREAMING_SNAKE_CASE_ : Tuple = LMSDiscreteScheduler.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , subfolder='''scheduler''') SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , scheduler=lowercase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : int = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=20 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Dict = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array( [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2
318
1
"""simple docstring""" import math import flax.linen as nn import jax.numpy as jnp def _A (__a , __a , __a = 1 , __a = 1 , __a = 1.0e4 , __a = False , __a = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, f'Embedding dimension {embedding_dim} should be even' SCREAMING_SNAKE_CASE_ : List[str] = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE_ : int = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE_ : Any = min_timescale * jnp.exp(jnp.arange(__a , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE_ : Dict = jnp.expand_dims(__a , 1 ) * jnp.expand_dims(__a , 0 ) # scale embeddings SCREAMING_SNAKE_CASE_ : Dict = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE_ : int = jnp.concatenate([jnp.cos(__a ), jnp.sin(__a )] , axis=1 ) else: SCREAMING_SNAKE_CASE_ : str = jnp.concatenate([jnp.sin(__a ), jnp.cos(__a )] , axis=1 ) SCREAMING_SNAKE_CASE_ : int = jnp.reshape(__a , [jnp.shape(__a )[0], embedding_dim] ) return signal class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' __UpperCamelCase = 3_2 __UpperCamelCase = jnp.floataa @nn.compact def __call__( self : Dict , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_1''')(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = nn.silu(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_2''')(lowercase_) return temb class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' __UpperCamelCase = 3_2 __UpperCamelCase = False __UpperCamelCase = 1 @nn.compact def __call__( self : str , lowercase_ : Optional[int]): '''simple docstring''' return get_sinusoidal_embeddings( lowercase_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift)
318
"""simple docstring""" from scipy.stats import pearsonr import datasets UpperCAmelCase_ : List[Any] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ UpperCAmelCase_ : Optional[int] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ UpperCAmelCase_ : Tuple = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float'''), '''references''': datasets.Value('''float'''), }) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=False): '''simple docstring''' if return_pvalue: SCREAMING_SNAKE_CASE_ : int = pearsonr(lowercase_ , lowercase_) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(lowercase_ , lowercase_)[0])}
318
1
"""simple docstring""" # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def _A (__a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [False] * len(__a ) SCREAMING_SNAKE_CASE_ : Any = [-1] * len(__a ) def dfs(__a , __a ): SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : Optional[Any] = c for u in graph[v]: if not visited[u]: dfs(__a , 1 - c ) for i in range(len(__a ) ): if not visited[i]: dfs(__a , 0 ) for i in range(len(__a ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph UpperCAmelCase_ : Optional[int] = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
318
"""simple docstring""" import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class lowerCAmelCase__ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any , lowercase_ : Dict[str, int] , lowercase_ : List[str] , lowercase_ : int = None , lowercase_ : int = None): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : str = pad_token_id SCREAMING_SNAKE_CASE_ : Optional[int] = max_length SCREAMING_SNAKE_CASE_ : Dict = vocab SCREAMING_SNAKE_CASE_ : Dict = merges SCREAMING_SNAKE_CASE_ : Union[str, Any] = BytePairTokenizer(lowercase_ , lowercase_ , sequence_length=lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : GPTaTokenizer , *lowercase_ : Optional[Any] , **lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = [''' '''.join(lowercase_) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE_ : str = tokenizer.get_vocab() return cls(lowercase_ , lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowercase_ : Union[str, os.PathLike] , *lowercase_ : List[str] , **lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = GPTaTokenizer.from_pretrained(lowercase_ , *lowercase_ , **lowercase_) return cls.from_tokenizer(lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : List[Any]): '''simple docstring''' return cls(**lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[Any] , lowercase_ : int = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.tf_tokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.ones_like(lowercase_) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = pad_model_inputs( lowercase_ , max_seq_length=lowercase_ , pad_value=self.pad_token_id) return {"attention_mask": attention_mask, "input_ids": input_ids}
318
1
"""simple docstring""" import unittest from transformers import DonutProcessor UpperCAmelCase_ : Optional[Any] = """naver-clova-ix/donut-base""" class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = DonutProcessor.from_pretrained(lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } SCREAMING_SNAKE_CASE_ : Any = ( '''<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>''' ) SCREAMING_SNAKE_CASE_ : Any = self.processor.tokenajson(lowercase_) self.assertDictEqual(lowercase_ , lowercase_)
318
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) SCREAMING_SNAKE_CASE_ : Dict = { '''do_resize''': True, '''size''': {'''height''': 224, '''width''': 224}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], '''do_convert_rgb''': True, } SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , lowercase_) with open(self.image_processor_file , '''w''' , encoding='''utf-8''') as fp: json.dump(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , **lowercase_ : str): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , **lowercase_ : List[Any]): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , **lowercase_ : str): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] SCREAMING_SNAKE_CASE_ : Dict = [Image.fromarray(np.moveaxis(lowercase_ , 0 , -1)) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_slow.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : Any = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_fast.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , lowercase_) self.assertIsInstance(processor_fast.tokenizer , lowercase_) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , lowercase_) self.assertIsInstance(processor_fast.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_image_processor(do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=lowercase_) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , lowercase_) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Any = image_processor(lowercase_ , return_tensors='''np''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor(images=lowercase_ , return_tensors='''np''') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : str = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Optional[Any] = processor(text=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer(lowercase_) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : int = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']) # test if it raises when no input is passed with pytest.raises(lowercase_): processor() def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_ : Optional[int] = processor.batch_decode(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.batch_decode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Dict = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Dict = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Dict = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
318
1
"""simple docstring""" import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): UpperCAmelCase_ : str = { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: UpperCAmelCase_ : Any = { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = (images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ : Dict = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE_ : str = numpy_to_pil(__a ) return images def _A (__a ) -> List[str]: """simple docstring""" if images.ndim == 3: SCREAMING_SNAKE_CASE_ : Tuple = images[None, ...] SCREAMING_SNAKE_CASE_ : Optional[Any] = (images * 2_55).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images SCREAMING_SNAKE_CASE_ : List[Any] = [Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(__a ) for image in images] return pil_images
318
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "rwkv" __UpperCamelCase = {"max_position_embeddings": "context_length"} def __init__( self : Union[str, Any] , lowercase_ : Any=50277 , lowercase_ : str=1024 , lowercase_ : List[str]=4096 , lowercase_ : Optional[Any]=32 , lowercase_ : Any=None , lowercase_ : Any=None , lowercase_ : List[Any]=1e-5 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=0 , lowercase_ : int=6 , lowercase_ : Tuple=False , lowercase_ : Any=True , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Any = context_length SCREAMING_SNAKE_CASE_ : int = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size SCREAMING_SNAKE_CASE_ : int = intermediate_size if intermediate_size is not None else 4 * hidden_size SCREAMING_SNAKE_CASE_ : int = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : Optional[int] = rescale_every SCREAMING_SNAKE_CASE_ : Dict = use_cache SCREAMING_SNAKE_CASE_ : Dict = bos_token_id SCREAMING_SNAKE_CASE_ : Any = eos_token_id super().__init__( tie_word_embeddings=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_)
318
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable def _A (__a , __a , __a , __a = 1_00 , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = x_start SCREAMING_SNAKE_CASE_ : Any = fnc(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.0 for _ in range(__a ): # Approximates small segments of curve as linear and solve # for trapezoidal area SCREAMING_SNAKE_CASE_ : Any = (x_end - x_start) / steps + xa SCREAMING_SNAKE_CASE_ : Optional[int] = fnc(__a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step SCREAMING_SNAKE_CASE_ : str = xa SCREAMING_SNAKE_CASE_ : Any = fxa return area if __name__ == "__main__": def _A (__a ) -> List[Any]: """simple docstring""" return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") UpperCAmelCase_ : int = 10 while i <= 100000: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
318
"""simple docstring""" UpperCAmelCase_ : Optional[int] = 8.3_1_4_4_5_9_8 def _A (__a , __a ) -> float: """simple docstring""" if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example UpperCAmelCase_ : str = 300 UpperCAmelCase_ : str = 28 UpperCAmelCase_ : Any = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
318
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase_ : Union[str, Any] = 16 UpperCAmelCase_ : Any = 32 def _A (__a , __a = 16 , __a = "bert-base-cased" ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained(__a ) SCREAMING_SNAKE_CASE_ : List[str] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ : str = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset SCREAMING_SNAKE_CASE_ : Tuple = datasets.map( __a , batched=__a , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=__a ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__a ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__a , padding='''max_length''' , max_length=1_28 , return_tensors='''pt''' ) return tokenizer.pad(__a , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ : int = DataLoader( tokenized_datasets['''train'''] , shuffle=__a , collate_fn=__a , batch_size=__a ) SCREAMING_SNAKE_CASE_ : Any = DataLoader( tokenized_datasets['''validation'''] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader def _A (__a , __a , __a , __a ) -> Optional[Any]: """simple docstring""" model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = 0 for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(**__a ) SCREAMING_SNAKE_CASE_ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__a ) - 1: SCREAMING_SNAKE_CASE_ : List[str] = predictions[: len(eval_dataloader.dataset ) - samples_seen] SCREAMING_SNAKE_CASE_ : Optional[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__a , references=__a , ) SCREAMING_SNAKE_CASE_ : List[Any] = metric.compute() return eval_metric["accuracy"] def _A (__a , __a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ : str = config['''lr'''] SCREAMING_SNAKE_CASE_ : int = int(config['''num_epochs'''] ) SCREAMING_SNAKE_CASE_ : Any = int(config['''seed'''] ) SCREAMING_SNAKE_CASE_ : str = int(config['''batch_size'''] ) SCREAMING_SNAKE_CASE_ : List[Any] = args.model_name_or_path set_seed(__a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = get_dataloaders(__a , __a , __a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForSequenceClassification.from_pretrained(__a , return_dict=__a ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ : str = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) SCREAMING_SNAKE_CASE_ : Optional[Any] = optimizer_cls(params=model.parameters() , lr=__a ) if accelerator.state.deepspeed_plugin is not None: SCREAMING_SNAKE_CASE_ : str = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : List[str] = (len(__a ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): SCREAMING_SNAKE_CASE_ : Optional[int] = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=0 , num_training_steps=__a , ) else: SCREAMING_SNAKE_CASE_ : int = DummyScheduler(__a , total_num_steps=__a , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = accelerator.prepare( __a , __a , __a , __a , __a ) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE_ : Optional[int] = 0 # We also need to keep track of the stating epoch so files are named properly SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : int = evaluate.load('''glue''' , '''mrpc''' ) SCREAMING_SNAKE_CASE_ : Tuple = num_epochs if args.partial_train_epoch is not None: SCREAMING_SNAKE_CASE_ : Dict = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) SCREAMING_SNAKE_CASE_ : Optional[int] = args.resume_from_checkpoint.split('''epoch_''' )[1] SCREAMING_SNAKE_CASE_ : int = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break SCREAMING_SNAKE_CASE_ : List[Any] = int(__a ) + 1 SCREAMING_SNAKE_CASE_ : int = evaluation_loop(__a , __a , __a , __a ) accelerator.print('''resumed checkpoint performance:''' , __a ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''' , lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''' , optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir , f'state_{starting_epoch-1}.json' ) , '''r''' ) as f: SCREAMING_SNAKE_CASE_ : int = json.load(__a ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model SCREAMING_SNAKE_CASE_ : Dict = {} for epoch in range(__a , __a ): model.train() for step, batch in enumerate(__a ): SCREAMING_SNAKE_CASE_ : Tuple = model(**__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = outputs.loss SCREAMING_SNAKE_CASE_ : Dict = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 SCREAMING_SNAKE_CASE_ : Dict = f'epoch_{epoch}' SCREAMING_SNAKE_CASE_ : int = os.path.join(args.output_dir , __a ) accelerator.save_state(__a ) SCREAMING_SNAKE_CASE_ : Tuple = evaluation_loop(__a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = accuracy SCREAMING_SNAKE_CASE_ : Optional[Any] = lr_scheduler.get_lr()[0] SCREAMING_SNAKE_CASE_ : List[Any] = optimizer.param_groups[0]['''lr'''] SCREAMING_SNAKE_CASE_ : Optional[int] = epoch SCREAMING_SNAKE_CASE_ : Union[str, Any] = overall_step accelerator.print(f'epoch {epoch}:' , __a ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f'state_{epoch}.json' ) , '''w''' ) as f: json.dump(__a , __a ) def _A () -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=__a , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=__a , ) parser.add_argument( '''--output_dir''' , type=__a , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--resume_from_checkpoint''' , type=__a , default=__a , help='''If the training should continue from a checkpoint folder.''' , ) parser.add_argument( '''--partial_train_epoch''' , type=__a , default=__a , help='''If passed, the training will stop after this number of epochs.''' , ) parser.add_argument( '''--num_epochs''' , type=__a , default=2 , help='''Number of train epochs.''' , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE_ : str = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(__a , __a ) if __name__ == "__main__": main()
318
"""simple docstring""" import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList UpperCAmelCase_ : Union[str, Any] = ["""\nclass""", """\ndef""", """\n#""", """\n@""", """\nprint""", """\nif"""] class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : int=None , lowercase_ : Dict=1): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = dataset SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase_) if n_tasks is None else n_tasks SCREAMING_SNAKE_CASE_ : Optional[int] = n_copies def __iter__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for task in range(self.n_tasks): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip()) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowercase_ , padding=lowercase_ , return_tensors='''pt''') for task in range(self.n_tasks): for _ in range(self.n_copies): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = start_length SCREAMING_SNAKE_CASE_ : List[Any] = eof_strings SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer def __call__( self : Optional[int] , lowercase_ : Any , lowercase_ : int , **lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.tokenizer.batch_decode(input_ids[:, self.start_length :]) SCREAMING_SNAKE_CASE_ : Tuple = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings)) return all(lowercase_) def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.split('''(%s)''' % '''|'''.join(__a ) , __a ) # last string should be "" return "".join(string_list[:-2] ) def _A (__a , __a , __a , __a , __a , __a=20 , **__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = defaultdict(__a ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__a ) ): with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] = batch['''ids'''].shape[-1] SCREAMING_SNAKE_CASE_ : Tuple = accelerator.unwrap_model(__a ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']] , num_return_sequences=__a , **__a ) # each task is generated batch_size times SCREAMING_SNAKE_CASE_ : List[Any] = batch['''task_id'''].repeat(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.pad_across_processes( __a , dim=1 , pad_index=tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) SCREAMING_SNAKE_CASE_ : int = generated_tokens.cpu().numpy() SCREAMING_SNAKE_CASE_ : Optional[Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__a , __a ): gen_token_dict[task].append(__a ) SCREAMING_SNAKE_CASE_ : int = [[] for _ in range(__a )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) code_gens[task].append(remove_last_block(__a ) ) return code_gens def _A () -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = HfArgumentParser(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric SCREAMING_SNAKE_CASE_ : Any = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing SCREAMING_SNAKE_CASE_ : str = '''false''' if args.num_workers is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() set_seed(args.seed , device_specific=__a ) # Load model and tokenizer SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.eos_token SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings SCREAMING_SNAKE_CASE_ : List[str] = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0 , __a , __a )] ), } # Load evaluation dataset and metric SCREAMING_SNAKE_CASE_ : Optional[int] = load_dataset('''openai_humaneval''' ) SCREAMING_SNAKE_CASE_ : str = load_metric('''code_eval''' ) SCREAMING_SNAKE_CASE_ : int = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) SCREAMING_SNAKE_CASE_ : List[str] = args.n_samples // args.batch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = TokenizedDataset(__a , human_eval['''test'''] , n_copies=__a , n_tasks=__a ) # do not confuse args.batch_size, which is actually the num_return_sequences SCREAMING_SNAKE_CASE_ : Optional[int] = DataLoader(__a , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: SCREAMING_SNAKE_CASE_ : Any = code_eval_metric.compute(references=[''''''] , predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = accelerator.prepare(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = complete_code( __a , __a , __a , __a , n_tasks=__a , batch_size=args.batch_size , **__a , ) if accelerator.is_main_process: SCREAMING_SNAKE_CASE_ : int = [] for task in tqdm(range(__a ) ): SCREAMING_SNAKE_CASE_ : Tuple = human_eval['''test'''][task]['''test'''] SCREAMING_SNAKE_CASE_ : Tuple = f'check({human_eval["test"][task]["entry_point"]})' references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = code_eval_metric.compute( references=__a , predictions=__a , num_workers=args.num_workers ) print(f'Results: {pass_at_k}' ) # Save results to json file with open(args.output_file , '''w''' ) as fp: json.dump(__a , __a ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
318
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Any , lowercase_ : List[Any]=13 , lowercase_ : List[str]=2 , lowercase_ : Optional[int]=24 , lowercase_ : List[Any]=16 , lowercase_ : Dict=True , lowercase_ : Dict=True , lowercase_ : Tuple=32 , lowercase_ : Tuple=5 , lowercase_ : Optional[Any]=4 , lowercase_ : Dict=37 , lowercase_ : int="gelu" , lowercase_ : Tuple=0.1 , lowercase_ : Optional[int]=0.1 , lowercase_ : Tuple=10 , lowercase_ : str=0.02 , lowercase_ : Optional[Any]=None , lowercase_ : List[str]=2 , lowercase_ : List[Any]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : Tuple = batch_size SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : List[Any] = max_length SCREAMING_SNAKE_CASE_ : Dict = num_mel_bins SCREAMING_SNAKE_CASE_ : Dict = is_training SCREAMING_SNAKE_CASE_ : Dict = use_labels SCREAMING_SNAKE_CASE_ : Dict = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Dict = hidden_act SCREAMING_SNAKE_CASE_ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : int = frequency_stride SCREAMING_SNAKE_CASE_ : Tuple = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) SCREAMING_SNAKE_CASE_ : int = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 SCREAMING_SNAKE_CASE_ : Dict = (self.max_length - self.patch_size) // self.time_stride + 1 SCREAMING_SNAKE_CASE_ : Any = frequency_out_dimension * time_out_dimension SCREAMING_SNAKE_CASE_ : Optional[int] = num_patches + 2 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]) SCREAMING_SNAKE_CASE_ : int = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_config() return config, input_values, labels def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = ASTModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : str = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''input_values''': input_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) __UpperCamelCase = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : List[str]): '''simple docstring''' if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = ASTModelTester(self) SCREAMING_SNAKE_CASE_ : str = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase_) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) SCREAMING_SNAKE_CASE_ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_ , nn.Linear)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Dict = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : List[Any] = ['''input_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Dict = ASTModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = torchaudio.load(__a ) return audio, sampling_rate @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''') if is_torchaudio_available() else None ) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.default_feature_extractor SCREAMING_SNAKE_CASE_ : Optional[Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_feature_extractor SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = prepare_audio() SCREAMING_SNAKE_CASE_ : int = audio.squeeze().numpy() SCREAMING_SNAKE_CASE_ : str = feature_extractor(lowercase_ , sampling_rate=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : List[Any] = torch.Size((1, 527)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.87_60, -7.00_42, -8.66_02]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "feature_extractor"] __UpperCamelCase = "TvltImageProcessor" __UpperCamelCase = "TvltFeatureExtractor" def __init__( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(image_processor=lowercase_ , feature_extractor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = feature_extractor def __call__( self : Any , lowercase_ : str=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : str=None , lowercase_ : int=False , lowercase_ : Union[str, Any]=False , *lowercase_ : List[Any] , **lowercase_ : List[str] , ): '''simple docstring''' if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''') SCREAMING_SNAKE_CASE_ : Any = None if images is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor(lowercase_ , mask_pixel=lowercase_ , *lowercase_ , **lowercase_) if images_mixed is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , is_mixed=lowercase_ , *lowercase_ , **lowercase_) if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor( lowercase_ , *lowercase_ , sampling_rate=lowercase_ , mask_audio=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {} if audio is not None: output_dict.update(lowercase_) if images is not None: output_dict.update(lowercase_) if images_mixed_dict is not None: output_dict.update(lowercase_) return output_dict @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
318
1
"""simple docstring""" from cva import destroyAllWindows, imread, imshow, waitKey def _A (__a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(__a ): for j in range(__a ): SCREAMING_SNAKE_CASE_ : List[str] = [2_55, 2_55, 2_55] - img[i][j] return img if __name__ == "__main__": # read original image UpperCAmelCase_ : Dict = imread("""image_data/lena.jpg""", 1) # convert to its negative UpperCAmelCase_ : Dict = convert_to_negative(img) # show result image imshow("""negative of original image""", img) waitKey(0) destroyAllWindows()
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "SpeechT5FeatureExtractor" __UpperCamelCase = "SpeechT5Tokenizer" def __init__( self : Any , lowercase_ : Dict , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(lowercase_ , lowercase_) def __call__( self : List[Any] , *lowercase_ : List[Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''audio''' , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.pop('''text''' , lowercase_) SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('''text_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''audio_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''sampling_rate''' , lowercase_) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''') if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''') if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''') if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor(lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) elif text is not None: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = None if audio_target is not None: SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extractor(audio_target=lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = targets['''input_values'''] elif text_target is not None: SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : int = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = labels SCREAMING_SNAKE_CASE_ : Optional[Any] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Any = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : Tuple , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''input_values''' , lowercase_) SCREAMING_SNAKE_CASE_ : int = kwargs.pop('''input_ids''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''labels''' , lowercase_) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''') if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''') if input_values is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) elif input_ids is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.pad(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : List[Any] = None if labels is not None: if "input_ids" in labels or (isinstance(lowercase_ , lowercase_) and "input_ids" in labels[0]): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer.pad(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Dict = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.feature_size SCREAMING_SNAKE_CASE_ : Optional[int] = self.feature_extractor.num_mel_bins SCREAMING_SNAKE_CASE_ : str = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : str = feature_size_hack SCREAMING_SNAKE_CASE_ : Dict = targets['''input_values'''] else: SCREAMING_SNAKE_CASE_ : List[Any] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Dict = labels SCREAMING_SNAKE_CASE_ : List[str] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowercase_ : Optional[int] , **lowercase_ : Tuple): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *lowercase_ : Dict , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_)
318
1
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = 42 class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ ): '''simple docstring''' @register_to_config def __init__( self : str , lowercase_ : int = 32 , lowercase_ : int = 64 , lowercase_ : int = 20 , lowercase_ : int = 768 , lowercase_ : Any=77 , lowercase_ : Optional[int]=4 , lowercase_ : float = 0.0 , lowercase_ : str = "silu" , lowercase_ : Optional[str] = None , lowercase_ : Optional[str] = None , lowercase_ : Optional[str] = "linear" , lowercase_ : Optional[str] = "prd" , lowercase_ : Optional[int] = None , lowercase_ : Optional[int] = None , lowercase_ : Optional[int] = None , ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Union[str, Any] = attention_head_dim SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads * attention_head_dim SCREAMING_SNAKE_CASE_ : Union[str, Any] = additional_embeddings SCREAMING_SNAKE_CASE_ : List[Any] = time_embed_dim or inner_dim SCREAMING_SNAKE_CASE_ : Dict = embedding_proj_dim or embedding_dim SCREAMING_SNAKE_CASE_ : Any = clip_embed_dim or embedding_dim SCREAMING_SNAKE_CASE_ : Any = Timesteps(lowercase_ , lowercase_ , 0) SCREAMING_SNAKE_CASE_ : List[str] = TimestepEmbedding(lowercase_ , lowercase_ , out_dim=lowercase_ , act_fn=lowercase_) SCREAMING_SNAKE_CASE_ : Any = nn.Linear(lowercase_ , lowercase_) if embedding_proj_norm_type is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = None elif embedding_proj_norm_type == "layer": SCREAMING_SNAKE_CASE_ : int = nn.LayerNorm(lowercase_) else: raise ValueError(F'unsupported embedding_proj_norm_type: {embedding_proj_norm_type}') SCREAMING_SNAKE_CASE_ : List[Any] = nn.Linear(lowercase_ , lowercase_) if encoder_hid_proj_type is None: SCREAMING_SNAKE_CASE_ : List[str] = None elif encoder_hid_proj_type == "linear": SCREAMING_SNAKE_CASE_ : Union[str, Any] = nn.Linear(lowercase_ , lowercase_) else: raise ValueError(F'unsupported encoder_hid_proj_type: {encoder_hid_proj_type}') SCREAMING_SNAKE_CASE_ : Tuple = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , lowercase_)) if added_emb_type == "prd": SCREAMING_SNAKE_CASE_ : str = nn.Parameter(torch.zeros(1 , 1 , lowercase_)) elif added_emb_type is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = None else: raise ValueError( F'`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.') SCREAMING_SNAKE_CASE_ : List[str] = nn.ModuleList( [ BasicTransformerBlock( lowercase_ , lowercase_ , lowercase_ , dropout=lowercase_ , activation_fn='''gelu''' , attention_bias=lowercase_ , ) for d in range(lowercase_) ]) if norm_in_type == "layer": SCREAMING_SNAKE_CASE_ : Union[str, Any] = nn.LayerNorm(lowercase_) elif norm_in_type is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = None else: raise ValueError(F'Unsupported norm_in_type: {norm_in_type}.') SCREAMING_SNAKE_CASE_ : List[str] = nn.LayerNorm(lowercase_) SCREAMING_SNAKE_CASE_ : str = nn.Linear(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_00_00.0) causal_attention_mask.triu_(1) SCREAMING_SNAKE_CASE_ : Union[str, Any] = causal_attention_mask[None, ...] self.register_buffer('''causal_attention_mask''' , lowercase_ , persistent=lowercase_) SCREAMING_SNAKE_CASE_ : int = nn.Parameter(torch.zeros(1 , lowercase_)) SCREAMING_SNAKE_CASE_ : str = nn.Parameter(torch.zeros(1 , lowercase_)) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} def fn_recursive_add_processors(lowercase_ : str , lowercase_ : torch.nn.Module , lowercase_ : Dict[str, AttentionProcessor]): if hasattr(lowercase_ , '''set_processor'''): SCREAMING_SNAKE_CASE_ : str = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'{name}.{sub_name}' , lowercase_ , lowercase_) return processors for name, module in self.named_children(): fn_recursive_add_processors(lowercase_ , lowercase_ , lowercase_) return processors def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Union[AttentionProcessor, Dict[str, AttentionProcessor]]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = len(self.attn_processors.keys()) if isinstance(lowercase_ , lowercase_) and len(lowercase_) != count: raise ValueError( F'A dict of processors was passed, but the number of processors {len(lowercase_)} does not match the' F' number of attention layers: {count}. Please make sure to pass {count} processor classes.') def fn_recursive_attn_processor(lowercase_ : str , lowercase_ : torch.nn.Module , lowercase_ : List[str]): if hasattr(lowercase_ , '''set_processor'''): if not isinstance(lowercase_ , lowercase_): module.set_processor(lowercase_) else: module.set_processor(processor.pop(F'{name}.processor')) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'{name}.{sub_name}' , lowercase_ , lowercase_) for name, module in self.named_children(): fn_recursive_attn_processor(lowercase_ , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' self.set_attn_processor(AttnProcessor()) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Optional[int] , lowercase_ : Union[torch.Tensor, float, int] , lowercase_ : torch.FloatTensor , lowercase_ : Optional[torch.FloatTensor] = None , lowercase_ : Optional[torch.BoolTensor] = None , lowercase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = hidden_states.shape[0] SCREAMING_SNAKE_CASE_ : Dict = timestep if not torch.is_tensor(lowercase_): SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device) elif torch.is_tensor(lowercase_) and len(timesteps.shape) == 0: SCREAMING_SNAKE_CASE_ : List[Any] = timesteps[None].to(hidden_states.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML SCREAMING_SNAKE_CASE_ : List[Any] = timesteps * torch.ones(lowercase_ , dtype=timesteps.dtype , device=timesteps.device) SCREAMING_SNAKE_CASE_ : Optional[int] = self.time_proj(lowercase_) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. SCREAMING_SNAKE_CASE_ : int = timesteps_projected.to(dtype=self.dtype) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.time_embedding(lowercase_) if self.embedding_proj_norm is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.embedding_proj_norm(lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.embedding_proj(lowercase_) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: SCREAMING_SNAKE_CASE_ : int = self.encoder_hidden_states_proj(lowercase_) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError('''`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set''') SCREAMING_SNAKE_CASE_ : str = self.proj_in(lowercase_) SCREAMING_SNAKE_CASE_ : int = self.positional_embedding.to(hidden_states.dtype) SCREAMING_SNAKE_CASE_ : Any = [] SCREAMING_SNAKE_CASE_ : List[Any] = 0 if encoder_hidden_states is not None: additional_embeds.append(lowercase_) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape) == 2: SCREAMING_SNAKE_CASE_ : Optional[Any] = proj_embeddings[:, None, :] if len(hidden_states.shape) == 2: SCREAMING_SNAKE_CASE_ : Union[str, Any] = hidden_states[:, None, :] SCREAMING_SNAKE_CASE_ : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.prd_embedding.to(hidden_states.dtype).expand(lowercase_ , -1 , -1) additional_embeds.append(lowercase_) SCREAMING_SNAKE_CASE_ : Any = torch.cat( lowercase_ , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens SCREAMING_SNAKE_CASE_ : Dict = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: SCREAMING_SNAKE_CASE_ : Tuple = F.pad( lowercase_ , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_states + positional_embeddings if attention_mask is not None: SCREAMING_SNAKE_CASE_ : Any = (1 - attention_mask.to(hidden_states.dtype)) * -1_00_00.0 SCREAMING_SNAKE_CASE_ : Tuple = F.pad(lowercase_ , (0, self.additional_embeddings) , value=0.0) SCREAMING_SNAKE_CASE_ : Optional[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype) SCREAMING_SNAKE_CASE_ : Union[str, Any] = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0) if self.norm_in is not None: SCREAMING_SNAKE_CASE_ : List[Any] = self.norm_in(lowercase_) for block in self.transformer_blocks: SCREAMING_SNAKE_CASE_ : Optional[int] = block(lowercase_ , attention_mask=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.norm_out(lowercase_) if self.prd_embedding is not None: SCREAMING_SNAKE_CASE_ : Tuple = hidden_states[:, -1] else: SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_states[:, additional_embeddings_len:] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.proj_to_clip_embeddings(lowercase_) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
318
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.inf def set_batch_size(__a ) -> None: nonlocal batch_size if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__a , __a ) and feature.dtype == "binary": SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__a , __a ) return None if batch_size is np.inf else batch_size class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , lowercase_ : NestedDataStructureLike[PathLike] , lowercase_ : Optional[NamedSplit] = None , lowercase_ : Optional[Features] = None , lowercase_ : str = None , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : Optional[int] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , split=lowercase_ , features=lowercase_ , cache_dir=lowercase_ , keep_in_memory=lowercase_ , streaming=lowercase_ , num_proc=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = path_or_paths if isinstance(lowercase_ , lowercase_) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_ : Any = _PACKAGED_DATASETS_MODULES['''parquet'''][1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = Parquet( cache_dir=lowercase_ , data_files=lowercase_ , features=lowercase_ , hash=lowercase_ , **lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE_ : str = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None self.builder.download_and_prepare( download_config=lowercase_ , download_mode=lowercase_ , verification_mode=lowercase_ , base_path=lowercase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_ : Any = self.builder.as_dataset( split=self.split , verification_mode=lowercase_ , in_memory=self.keep_in_memory) return dataset class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Dataset , lowercase_ : Union[PathLike, BinaryIO] , lowercase_ : Optional[int] = None , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = dataset SCREAMING_SNAKE_CASE_ : Dict = path_or_buf SCREAMING_SNAKE_CASE_ : List[Any] = batch_size or get_writer_batch_size(dataset.features) SCREAMING_SNAKE_CASE_ : Any = parquet_writer_kwargs def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , '''wb+''') as buffer: SCREAMING_SNAKE_CASE_ : Optional[Any] = self._write(file_obj=lowercase_ , batch_size=lowercase_ , **self.parquet_writer_kwargs) else: SCREAMING_SNAKE_CASE_ : str = self._write(file_obj=self.path_or_buf , batch_size=lowercase_ , **self.parquet_writer_kwargs) return written def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : BinaryIO , lowercase_ : int , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = parquet_writer_kwargs.pop('''path_or_buf''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dataset.features.arrow_schema SCREAMING_SNAKE_CASE_ : Tuple = pq.ParquetWriter(lowercase_ , schema=lowercase_ , **lowercase_) for offset in logging.tqdm( range(0 , len(self.dataset) , lowercase_) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): SCREAMING_SNAKE_CASE_ : List[Any] = query_table( table=self.dataset._data , key=slice(lowercase_ , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(lowercase_) written += batch.nbytes writer.close() return written
318
1
"""simple docstring""" def _A (__a ) -> list: """simple docstring""" return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(__a ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__("""doctest""").testmod()
318
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = ["""model.decoder.embed_positions.weights"""] def _A (__a ) -> Dict: """simple docstring""" if "emb" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def _A (__a , __a ) -> Tuple[Dict, Dict]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(state_dict.keys() ) SCREAMING_SNAKE_CASE_ : int = {} for key in keys: SCREAMING_SNAKE_CASE_ : int = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ : int = rename_keys(__a ) if "in_proj_weight" in key: # split fused qkv proj SCREAMING_SNAKE_CASE_ : List[str] = val[:hidden_size, :] SCREAMING_SNAKE_CASE_ : List[str] = val[hidden_size : 2 * hidden_size, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: SCREAMING_SNAKE_CASE_ : int = val else: SCREAMING_SNAKE_CASE_ : Any = val return state_dict, enc_dec_proj_state_dict def _A (__a ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values SCREAMING_SNAKE_CASE_ : Optional[int] = 10_24 SCREAMING_SNAKE_CASE_ : Tuple = 24 SCREAMING_SNAKE_CASE_ : Optional[Any] = 16 elif checkpoint == "medium": SCREAMING_SNAKE_CASE_ : List[str] = 15_36 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : Optional[int] = 24 elif checkpoint == "large": SCREAMING_SNAKE_CASE_ : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : int = 32 else: raise ValueError(f'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' ) SCREAMING_SNAKE_CASE_ : List[Any] = MusicgenDecoderConfig( hidden_size=__a , ffn_dim=hidden_size * 4 , num_hidden_layers=__a , num_attention_heads=__a , ) return config @torch.no_grad() def _A (__a , __a=None , __a=None , __a="cpu" ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = MusicGen.get_pretrained(__a , device=__a ) SCREAMING_SNAKE_CASE_ : Dict = decoder_config_from_checkpoint(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = fairseq_model.lm.state_dict() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = rename_state_dict( __a , hidden_size=decoder_config.hidden_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = TaEncoderModel.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : List[str] = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) SCREAMING_SNAKE_CASE_ : int = MusicgenForCausalLM(__a ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = decoder.load_state_dict(__a , strict=__a ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__a ) if len(__a ) > 0: raise ValueError(f'Missing key(s) in state_dict: {missing_keys}' ) if len(__a ) > 0: raise ValueError(f'Unexpected key(s) in state_dict: {unexpected_keys}' ) # init the composite model SCREAMING_SNAKE_CASE_ : str = MusicgenForConditionalGeneration(text_encoder=__a , audio_encoder=__a , decoder=__a ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__a ) # check we can do a forward pass SCREAMING_SNAKE_CASE_ : Dict = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=__a , decoder_input_ids=__a ).logits if logits.shape != (8, 1, 20_48): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : str = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) SCREAMING_SNAKE_CASE_ : Tuple = MusicgenProcessor(feature_extractor=__a , tokenizer=__a ) # set the appropriate bos/pad token ids SCREAMING_SNAKE_CASE_ : str = 20_48 SCREAMING_SNAKE_CASE_ : List[Any] = 20_48 # set other default generation config params SCREAMING_SNAKE_CASE_ : int = int(30 * audio_encoder.config.frame_rate ) SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Optional[Any] = 3.0 if pytorch_dump_folder is not None: Path(__a ).mkdir(exist_ok=__a ) logger.info(f'Saving model {checkpoint} to {pytorch_dump_folder}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if repo_id: logger.info(f'Pushing model {checkpoint} to {repo_id}' ) model.push_to_hub(__a ) processor.push_to_hub(__a ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) UpperCAmelCase_ : Dict = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
318
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = { """google/vit-base-patch16-224""": """https://huggingface.co/vit-base-patch16-224/resolve/main/config.json""", # See all ViT models at https://huggingface.co/models?filter=vit } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "vit" def __init__( self : Any , lowercase_ : Union[str, Any]=768 , lowercase_ : str=12 , lowercase_ : Any=12 , lowercase_ : Optional[int]=3072 , lowercase_ : Any="gelu" , lowercase_ : Optional[int]=0.0 , lowercase_ : List[str]=0.0 , lowercase_ : int=0.02 , lowercase_ : int=1e-12 , lowercase_ : Dict=224 , lowercase_ : Any=16 , lowercase_ : Any=3 , lowercase_ : Optional[int]=True , lowercase_ : Optional[int]=16 , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Dict = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[str] = image_size SCREAMING_SNAKE_CASE_ : Optional[Any] = patch_size SCREAMING_SNAKE_CASE_ : Any = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : List[str] = encoder_stride class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = version.parse("1.11" ) @property def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) @property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return 1e-4
318
"""simple docstring""" from pathlib import Path import numpy as np from PIL import Image def _A (__a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def _A (__a ) -> np.ndarray: """simple docstring""" return (gray > 1_27) & (gray <= 2_55) def _A (__a , __a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = np.zeros_like(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE_ : Union[str, Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE_ : Optional[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE_ : Any = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCAmelCase_ : Dict = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" UpperCAmelCase_ : List[Any] = np.array(Image.open(lena_path)) # kernel to be applied UpperCAmelCase_ : Any = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCAmelCase_ : Tuple = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCAmelCase_ : List[str] = Image.fromarray(output).convert("""RGB""") pil_img.save("""result_dilation.png""")
318
1
"""simple docstring""" UpperCAmelCase_ : Optional[int] = { """A""": """.-""", """B""": """-...""", """C""": """-.-.""", """D""": """-..""", """E""": """.""", """F""": """..-.""", """G""": """--.""", """H""": """....""", """I""": """..""", """J""": """.---""", """K""": """-.-""", """L""": """.-..""", """M""": """--""", """N""": """-.""", """O""": """---""", """P""": """.--.""", """Q""": """--.-""", """R""": """.-.""", """S""": """...""", """T""": """-""", """U""": """..-""", """V""": """...-""", """W""": """.--""", """X""": """-..-""", """Y""": """-.--""", """Z""": """--..""", """1""": """.----""", """2""": """..---""", """3""": """...--""", """4""": """....-""", """5""": """.....""", """6""": """-....""", """7""": """--...""", """8""": """---..""", """9""": """----.""", """0""": """-----""", """&""": """.-...""", """@""": """.--.-.""", """:""": """---...""", """,""": """--..--""", """.""": """.-.-.-""", """'""": """.----.""", """\"""": """.-..-.""", """?""": """..--..""", """/""": """-..-.""", """=""": """-...-""", """+""": """.-.-.""", """-""": """-....-""", """(""": """-.--.""", """)""": """-.--.-""", """!""": """-.-.--""", """ """: """/""" } # Exclamation mark is not in ITU-R recommendation # fmt: on UpperCAmelCase_ : Any = {value: key for key, value in MORSE_CODE_DICT.items()} def _A (__a ) -> str: """simple docstring""" return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def _A (__a ) -> str: """simple docstring""" return "".join(REVERSE_DICT[char] for char in message.split() ) def _A () -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Morse code here!''' print(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = encrypt(__a ) print(__a ) SCREAMING_SNAKE_CASE_ : Any = decrypt(__a ) print(__a ) if __name__ == "__main__": main()
318
"""simple docstring""" from collections import defaultdict def _A (__a , __a ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = first_str.lower().strip() SCREAMING_SNAKE_CASE_ : List[Any] = second_str.lower().strip() # Remove whitespace SCREAMING_SNAKE_CASE_ : Dict = first_str.replace(''' ''' , '''''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = second_str.replace(''' ''' , '''''' ) # Strings of different lengths are not anagrams if len(__a ) != len(__a ): return False # Default values for count should be 0 SCREAMING_SNAKE_CASE_ : defaultdict[str, int] = defaultdict(__a ) # For each character in input strings, # increment count in the corresponding for i in range(len(__a ) ): 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() UpperCAmelCase_ : Any = input("""Enter the first string """).strip() UpperCAmelCase_ : Optional[int] = input("""Enter the second string """).strip() UpperCAmelCase_ : Union[str, Any] = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {'' if status else 'not '}anagrams.''')
318
1
"""simple docstring""" import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("""0.12.2"""): raise Exception("""requires fairseq >= 0.12.2""") if version.parse(fairseq.__version__) > version.parse("""2"""): raise Exception("""requires fairseq < v2""") logging.set_verbosity_info() UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = """Hello, World!""" UpperCAmelCase_ : Union[str, Any] = """en_XX""" def _A (__a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Path('''data_bin''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(__a ).parent ) , checkpoint_file=Path(__a ).name , _name='''xmod_base''' , arch='''xmod_base''' , task='''multilingual_masked_lm''' , data_name_or_path=str(__a ) , bpe='''sentencepiece''' , sentencepiece_model=str(Path(__a ).parent / '''sentencepiece.bpe.model''' ) , src_dict=str(data_dir / '''dict.txt''' ) , ) xmod.eval() # disable dropout print(__a ) SCREAMING_SNAKE_CASE_ : int = xmod.model.encoder.sentence_encoder SCREAMING_SNAKE_CASE_ : Optional[Any] = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , '''bottleneck''' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: SCREAMING_SNAKE_CASE_ : Union[str, Any] = xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our X-MOD config:''' , __a ) SCREAMING_SNAKE_CASE_ : Tuple = XmodForSequenceClassification(__a ) if classification_head else XmodForMaskedLM(__a ) model.eval() # Now let's copy all the weights. # Embeddings SCREAMING_SNAKE_CASE_ : Tuple = xmod_sent_encoder.embed_tokens.weight SCREAMING_SNAKE_CASE_ : Any = xmod_sent_encoder.embed_positions.weight SCREAMING_SNAKE_CASE_ : List[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. SCREAMING_SNAKE_CASE_ : int = xmod_sent_encoder.layernorm_embedding.weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer SCREAMING_SNAKE_CASE_ : List[str] = model.roberta.encoder.layer[i] SCREAMING_SNAKE_CASE_ : Optional[Any] = xmod_sent_encoder.layers[i] # self attention SCREAMING_SNAKE_CASE_ : Any = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('''Dimensions of self-attention weights do not match.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = xmod_layer.self_attn.q_proj.weight SCREAMING_SNAKE_CASE_ : str = xmod_layer.self_attn.q_proj.bias SCREAMING_SNAKE_CASE_ : List[Any] = xmod_layer.self_attn.k_proj.weight SCREAMING_SNAKE_CASE_ : Optional[Any] = xmod_layer.self_attn.k_proj.bias SCREAMING_SNAKE_CASE_ : Tuple = xmod_layer.self_attn.v_proj.weight SCREAMING_SNAKE_CASE_ : Dict = xmod_layer.self_attn.v_proj.bias # self-attention output SCREAMING_SNAKE_CASE_ : Optional[Any] = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('''Dimensions of self-attention output weights do not match.''' ) SCREAMING_SNAKE_CASE_ : int = xmod_layer.self_attn.out_proj.weight SCREAMING_SNAKE_CASE_ : Optional[int] = xmod_layer.self_attn.out_proj.bias SCREAMING_SNAKE_CASE_ : Dict = xmod_layer.self_attn_layer_norm.weight SCREAMING_SNAKE_CASE_ : Dict = xmod_layer.self_attn_layer_norm.bias # intermediate SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of intermediate weights do not match.''' ) SCREAMING_SNAKE_CASE_ : Dict = xmod_layer.fca.weight SCREAMING_SNAKE_CASE_ : Tuple = xmod_layer.fca.bias # output SCREAMING_SNAKE_CASE_ : Optional[int] = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of feed-forward weights do not match.''' ) SCREAMING_SNAKE_CASE_ : Tuple = xmod_layer.fca.weight SCREAMING_SNAKE_CASE_ : List[str] = xmod_layer.fca.bias SCREAMING_SNAKE_CASE_ : Union[str, Any] = xmod_layer.final_layer_norm.weight SCREAMING_SNAKE_CASE_ : Any = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: SCREAMING_SNAKE_CASE_ : str = xmod_layer.adapter_layer_norm.weight SCREAMING_SNAKE_CASE_ : int = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('''Lists of language adapters do not match.''' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = bert_output.adapter_modules[lang_code] SCREAMING_SNAKE_CASE_ : Dict = xmod_layer.adapter_modules[lang_code] SCREAMING_SNAKE_CASE_ : Any = from_adapter.fca.weight SCREAMING_SNAKE_CASE_ : Dict = from_adapter.fca.bias SCREAMING_SNAKE_CASE_ : Optional[Any] = from_adapter.fca.weight SCREAMING_SNAKE_CASE_ : Tuple = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: SCREAMING_SNAKE_CASE_ : str = xmod_sent_encoder.layer_norm.weight SCREAMING_SNAKE_CASE_ : str = xmod_sent_encoder.layer_norm.bias if classification_head: SCREAMING_SNAKE_CASE_ : Any = xmod.model.classification_heads['''mnli'''].dense.weight SCREAMING_SNAKE_CASE_ : List[Any] = xmod.model.classification_heads['''mnli'''].dense.bias SCREAMING_SNAKE_CASE_ : Union[str, Any] = xmod.model.classification_heads['''mnli'''].out_proj.weight SCREAMING_SNAKE_CASE_ : str = xmod.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head SCREAMING_SNAKE_CASE_ : Any = xmod.model.encoder.lm_head.dense.weight SCREAMING_SNAKE_CASE_ : List[Any] = xmod.model.encoder.lm_head.dense.bias SCREAMING_SNAKE_CASE_ : int = xmod.model.encoder.lm_head.layer_norm.weight SCREAMING_SNAKE_CASE_ : str = xmod.model.encoder.lm_head.layer_norm.bias SCREAMING_SNAKE_CASE_ : Optional[int] = xmod.model.encoder.lm_head.weight SCREAMING_SNAKE_CASE_ : int = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. SCREAMING_SNAKE_CASE_ : int = xmod.encode(__a ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(__a )[0] if classification_head: SCREAMING_SNAKE_CASE_ : List[Any] = xmod.model.classification_heads['''mnli'''](xmod.extract_features(__a ) ) else: SCREAMING_SNAKE_CASE_ : Dict = xmod.model(__a , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) SCREAMING_SNAKE_CASE_ : List[str] = torch.max(torch.abs(our_output - their_output ) ).item() print(f'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 SCREAMING_SNAKE_CASE_ : int = torch.allclose(__a , __a , atol=1e-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) Path(__a ).mkdir(parents=__a , exist_ok=__a ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) if __name__ == "__main__": UpperCAmelCase_ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--xmod_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head.""" ) UpperCAmelCase_ : Dict = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
318
"""simple docstring""" import argparse from collections import defaultdict import yaml UpperCAmelCase_ : Optional[Any] = """docs/source/en/_toctree.yml""" def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 SCREAMING_SNAKE_CASE_ : List[Any] = [key for key, value in counts.items() if value > 1] SCREAMING_SNAKE_CASE_ : int = [] for duplicate_key in duplicates: SCREAMING_SNAKE_CASE_ : List[str] = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(__a , key=lambda __a : s["title"].lower() ) def _A (__a=False ) -> Tuple: """simple docstring""" with open(__a , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE_ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE_ : str = content[api_idx]['''sections'''] # Then to the model doc SCREAMING_SNAKE_CASE_ : List[Any] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = api_doc[model_idx]['''sections'''] SCREAMING_SNAKE_CASE_ : str = [(idx, section) for idx, section in enumerate(__a ) if '''sections''' in section] SCREAMING_SNAKE_CASE_ : Optional[Any] = False for idx, modality_doc in modalities_docs: SCREAMING_SNAKE_CASE_ : List[str] = modality_doc['''sections'''] SCREAMING_SNAKE_CASE_ : Union[str, Any] = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: SCREAMING_SNAKE_CASE_ : str = True if overwrite: SCREAMING_SNAKE_CASE_ : Optional[int] = new_modality_doc if diff: if overwrite: SCREAMING_SNAKE_CASE_ : List[Any] = model_doc SCREAMING_SNAKE_CASE_ : int = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) 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__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Tuple = parser.parse_args() check_model_doc(args.fix_and_overwrite)
318
1
"""simple docstring""" from itertools import permutations def _A (__a ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAKE_CASE_ : List[str] = [7, 11, 13, 17] for i, test in enumerate(__a ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _A (__a = 10 ) -> int: """simple docstring""" return sum( int(''''''.join(map(__a , __a ) ) ) for num in permutations(range(__a ) ) if is_substring_divisible(__a ) ) if __name__ == "__main__": print(f'''{solution() = }''')
318
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
1
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "SpeechT5FeatureExtractor" __UpperCamelCase = "SpeechT5Tokenizer" def __init__( self : Any , lowercase_ : Dict , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(lowercase_ , lowercase_) def __call__( self : List[Any] , *lowercase_ : List[Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''audio''' , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.pop('''text''' , lowercase_) SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('''text_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''audio_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''sampling_rate''' , lowercase_) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''') if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''') if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''') if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor(lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) elif text is not None: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = None if audio_target is not None: SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extractor(audio_target=lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = targets['''input_values'''] elif text_target is not None: SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : int = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = labels SCREAMING_SNAKE_CASE_ : Optional[Any] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Any = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : Tuple , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''input_values''' , lowercase_) SCREAMING_SNAKE_CASE_ : int = kwargs.pop('''input_ids''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''labels''' , lowercase_) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''') if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''') if input_values is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) elif input_ids is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.pad(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : List[Any] = None if labels is not None: if "input_ids" in labels or (isinstance(lowercase_ , lowercase_) and "input_ids" in labels[0]): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer.pad(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Dict = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.feature_size SCREAMING_SNAKE_CASE_ : Optional[int] = self.feature_extractor.num_mel_bins SCREAMING_SNAKE_CASE_ : str = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : str = feature_size_hack SCREAMING_SNAKE_CASE_ : Dict = targets['''input_values'''] else: SCREAMING_SNAKE_CASE_ : List[Any] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Dict = labels SCREAMING_SNAKE_CASE_ : List[str] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowercase_ : Optional[int] , **lowercase_ : Tuple): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *lowercase_ : Dict , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_)
318
"""simple docstring""" from __future__ import annotations UpperCAmelCase_ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase_ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase_ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _A (__a , __a , __a , __a ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _A (__a ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _A (__a ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__a ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__a , __a , __a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = digit if sudoku(__a ) is not None: return grid SCREAMING_SNAKE_CASE_ : Any = 0 return None def _A (__a ) -> None: """simple docstring""" for row in grid: for cell in row: print(__a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") UpperCAmelCase_ : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
318
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 UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : int = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : Any = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : Optional[int] = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="</s>" , lowercase_ : Dict="</s>" , lowercase_ : Dict="<s>" , lowercase_ : List[Any]="<unk>" , lowercase_ : Tuple="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : str = 7 SCREAMING_SNAKE_CASE_ : int = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = 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' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : List[str] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : List[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : str = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : List[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self : str , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : List[Any] = {} SCREAMING_SNAKE_CASE_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Optional[int] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = False): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase_ , token_ids_a=lowercase_ , already_has_special_tokens=lowercase_) if token_ids_a is None: return [1] + ([0] * len(lowercase_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : int = self.sp_model.PieceToId(lowercase_) # 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 _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Optional[Any]): '''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 _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
318
"""simple docstring""" from itertools import permutations def _A (__a ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAKE_CASE_ : List[str] = [7, 11, 13, 17] for i, test in enumerate(__a ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _A (__a = 10 ) -> int: """simple docstring""" return sum( int(''''''.join(map(__a , __a ) ) ) for num in permutations(range(__a ) ) if is_substring_divisible(__a ) ) if __name__ == "__main__": print(f'''{solution() = }''')
318
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def _A (__a=None ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = argparse.ArgumentParser(add_help=__a , allow_abbrev=__a ) # The main config parser SCREAMING_SNAKE_CASE_ : Optional[Any] = config_command_parser(__a ) # The subparser to add commands to SCREAMING_SNAKE_CASE_ : List[Any] = config_parser.add_subparsers(title='''subcommands''' , dest='''subcommand''' ) # Then add other parsers with the parent parser default_command_parser(__a , parents=[parent_parser] ) update_command_parser(__a , parents=[parent_parser] ) return config_parser def _A () -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = get_config_parser() SCREAMING_SNAKE_CASE_ : str = config_parser.parse_args() if not hasattr(__a , '''func''' ): config_parser.print_help() exit(1 ) # Run args.func(__a ) if __name__ == "__main__": main()
318
"""simple docstring""" UpperCAmelCase_ : List[Any] = 9.8_0_6_6_5 def _A (__a , __a , __a = g ) -> float: """simple docstring""" if fluid_density <= 0: raise ValueError('''Impossible fluid density''' ) if volume < 0: raise ValueError('''Impossible Object volume''' ) if gravity <= 0: raise ValueError('''Impossible Gravity''' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
318
1
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def _A (__a , __a = True , __a = math.inf , __a = -math.inf , __a = math.inf , __a = -math.inf , __a = False , __a = 1_00 , __a = 0.01 , __a = 1 , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : int = search_prob SCREAMING_SNAKE_CASE_ : Tuple = start_temperate SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : List[Any] = None while not search_end: SCREAMING_SNAKE_CASE_ : List[Any] = current_state.score() if best_state is None or current_score > best_state.score(): SCREAMING_SNAKE_CASE_ : Tuple = current_state scores.append(__a ) iterations += 1 SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to SCREAMING_SNAKE_CASE_ : str = random.randint(0 , len(__a ) - 1 ) # picking a random neighbor SCREAMING_SNAKE_CASE_ : List[str] = neighbors.pop(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: SCREAMING_SNAKE_CASE_ : Any = change * -1 # in case we are finding minimum if change > 0: # improves the solution SCREAMING_SNAKE_CASE_ : List[Any] = picked_neighbor else: SCREAMING_SNAKE_CASE_ : List[Any] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability SCREAMING_SNAKE_CASE_ : Any = picked_neighbor SCREAMING_SNAKE_CASE_ : Optional[int] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor SCREAMING_SNAKE_CASE_ : Union[str, Any] = True else: SCREAMING_SNAKE_CASE_ : List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(__a ) , __a ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def _A (__a , __a ) -> Tuple: """simple docstring""" return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase_ : Optional[Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase_ : Dict = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( """The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ f'''and 50 > y > - 5 found via hill climbing: {local_min.score()}''' ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase_ : int = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase_ : Any = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( """The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """ f'''and 50 > y > - 5 found via hill climbing: {local_min.score()}''' ) def _A (__a , __a ) -> Optional[int]: """simple docstring""" return (3 * x**2) - (6 * y) UpperCAmelCase_ : str = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase_ : List[str] = simulated_annealing(prob, find_max=False, visualization=True) print( """The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ f'''{local_min.score()}''' ) UpperCAmelCase_ : Optional[int] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase_ : Any = simulated_annealing(prob, find_max=True, visualization=True) print( """The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """ f'''{local_min.score()}''' )
318
"""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. UpperCAmelCase_ : Union[str, Any] = abspath(join(dirname(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 _A (__a ) -> Union[str, Any]: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def _A (__a ) -> Any: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE_ : Optional[Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a , id=__a )
318
1
"""simple docstring""" import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = CpmAntTokenizer __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ '''<d>''', '''</d>''', '''<s>''', '''</s>''', '''</_>''', '''<unk>''', '''<pad>''', '''</n>''', '''我''', '''是''', '''C''', '''P''', '''M''', '''A''', '''n''', '''t''', ] SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) @tooslow def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = CpmAntTokenizer.from_pretrained('''openbmb/cpm-ant-10b''') SCREAMING_SNAKE_CASE_ : List[str] = '''今天天气真好!''' SCREAMING_SNAKE_CASE_ : Optional[int] = ['''今天''', '''天气''', '''真''', '''好''', '''!'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = '''今天天气真好!''' SCREAMING_SNAKE_CASE_ : List[str] = [tokenizer.bos_token] + tokens SCREAMING_SNAKE_CASE_ : Optional[Any] = [6, 9802, 14962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.decode(lowercase_) self.assertEqual(lowercase_ , lowercase_)
318
"""simple docstring""" import argparse import os import re import packaging.version UpperCAmelCase_ : Any = """examples/""" UpperCAmelCase_ : Optional[int] = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCAmelCase_ : List[Any] = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCAmelCase_ : Optional[int] = """README.md""" def _A (__a , __a , __a ) -> int: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Optional[Any] = f.read() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = REPLACE_PATTERNS[pattern] SCREAMING_SNAKE_CASE_ : Optional[int] = replace.replace('''VERSION''' , __a ) SCREAMING_SNAKE_CASE_ : Tuple = re_pattern.sub(__a , __a ) with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(__a ) def _A (__a ) -> int: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a , __a ) , __a , pattern='''examples''' ) def _A (__a , __a=False ) -> List[str]: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a , __a , __a ) if not patch: update_version_in_examples(__a ) def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' SCREAMING_SNAKE_CASE_ : Optional[int] = '''1. Want to contribute a new model?''' with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Tuple = f.readlines() # Find the start of the list. SCREAMING_SNAKE_CASE_ : Tuple = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Dict = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): SCREAMING_SNAKE_CASE_ : List[Any] = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__a ) def _A () -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] , '''r''' ) as f: SCREAMING_SNAKE_CASE_ : Any = f.read() SCREAMING_SNAKE_CASE_ : Dict = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def _A (__a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: SCREAMING_SNAKE_CASE_ : List[Any] = default_version.base_version elif patch: SCREAMING_SNAKE_CASE_ : int = f'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: SCREAMING_SNAKE_CASE_ : Any = f'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are you releasing? [{default_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = default_version print(f'Updating version to {version}.' ) global_version_update(__a , patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def _A () -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_version() SCREAMING_SNAKE_CASE_ : Any = f'{current_version.major}.{current_version.minor + 1}.0.dev0' SCREAMING_SNAKE_CASE_ : Union[str, Any] = current_version.base_version # Check with the user we got that right. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are we developing now? [{dev_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[int] = dev_version print(f'Updating version to {version}.' ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCAmelCase_ : int = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
318
1
"""simple docstring""" from __future__ import annotations def _A (__a , __a ) -> tuple[int, int]: """simple docstring""" if b == 0: return (1, 0) ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : Optional[Any] = extended_euclid(__a , a % b ) SCREAMING_SNAKE_CASE_ : Any = a // b return (y, x - k * y) def _A (__a , __a , __a , __a ) -> int: """simple docstring""" ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : int = extended_euclid(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = na * na SCREAMING_SNAKE_CASE_ : str = ra * x * na + ra * y * na return (n % m + m) % m def _A (__a , __a ) -> int: """simple docstring""" ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : List[str] = extended_euclid(__a , __a ) if b < 0: SCREAMING_SNAKE_CASE_ : int = (b % n + n) % n return b def _A (__a , __a , __a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = invert_modulo(__a , __a ), invert_modulo(__a , __a ) SCREAMING_SNAKE_CASE_ : Any = na * na SCREAMING_SNAKE_CASE_ : Any = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="""chinese_remainder_theorem""", verbose=True) testmod(name="""chinese_remainder_theorem2""", verbose=True) testmod(name="""invert_modulo""", verbose=True) testmod(name="""extended_euclid""", verbose=True)
318
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _A (__a , __a , __a=1e-12 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T SCREAMING_SNAKE_CASE_ : List[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T return jnp.matmul(__a , norm_emb_a.T ) class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxCLIPVisionModule(self.config.vision_config) SCREAMING_SNAKE_CASE_ : Tuple = nn.Dense(self.config.projection_dim , use_bias=lowercase_ , dtype=self.dtype) SCREAMING_SNAKE_CASE_ : List[str] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Dict = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,)) def __call__( self : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.vision_model(lowercase_)[1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.visual_projection(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.special_care_embeds) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs SCREAMING_SNAKE_CASE_ : Tuple = 0.0 SCREAMING_SNAKE_CASE_ : Dict = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment SCREAMING_SNAKE_CASE_ : Optional[int] = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : List[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=lowercase_) # Use a lower threshold if an image has any special care concept SCREAMING_SNAKE_CASE_ : Dict = is_special_care * 0.01 SCREAMING_SNAKE_CASE_ : str = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment SCREAMING_SNAKE_CASE_ : Any = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : Dict = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = CLIPConfig __UpperCamelCase = "clip_input" __UpperCamelCase = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Union[str, Any] , lowercase_ : CLIPConfig , lowercase_ : Optional[Tuple] = None , lowercase_ : int = 0 , lowercase_ : jnp.dtype = jnp.floataa , lowercase_ : bool = True , **lowercase_ : Any , ): '''simple docstring''' if input_shape is None: SCREAMING_SNAKE_CASE_ : List[str] = (1, 224, 224, 3) SCREAMING_SNAKE_CASE_ : List[Any] = self.module_class(config=lowercase_ , dtype=lowercase_ , **lowercase_) super().__init__(lowercase_ , lowercase_ , input_shape=lowercase_ , seed=lowercase_ , dtype=lowercase_ , _do_init=_do_init) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : jax.random.KeyArray , lowercase_ : Tuple , lowercase_ : FrozenDict = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = jax.random.normal(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = jax.random.split(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = {'''params''': params_rng, '''dropout''': dropout_rng} SCREAMING_SNAKE_CASE_ : List[Any] = self.module.init(lowercase_ , lowercase_)['''params'''] return random_params def __call__( self : List[Any] , lowercase_ : List[str] , lowercase_ : dict = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = jnp.transpose(lowercase_ , (0, 2, 3, 1)) return self.module.apply( {'''params''': params or self.params} , jnp.array(lowercase_ , dtype=jnp.floataa) , rngs={} , )
318
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : Any = logging.get_logger(__name__) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1_44, 1_92, 2_40] SCREAMING_SNAKE_CASE_ : Any = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE_ : str = [96, 1_20, 1_44] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE_ : Tuple = [64, 80, 96] SCREAMING_SNAKE_CASE_ : str = [16, 16, 24, 48, 64, 80, 3_20] SCREAMING_SNAKE_CASE_ : str = 0.05 SCREAMING_SNAKE_CASE_ : str = 2.0 if mobilevit_name.startswith('''deeplabv3_''' ): SCREAMING_SNAKE_CASE_ : str = 5_12 SCREAMING_SNAKE_CASE_ : Optional[Any] = 16 SCREAMING_SNAKE_CASE_ : str = 21 SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''pascal-voc-id2label.json''' else: SCREAMING_SNAKE_CASE_ : List[str] = 10_00 SCREAMING_SNAKE_CASE_ : List[Any] = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ : str = '''huggingface/label-files''' SCREAMING_SNAKE_CASE_ : Optional[Any] = json.load(open(hf_hub_download(__a , __a , repo_type='''dataset''' ) , '''r''' ) ) SCREAMING_SNAKE_CASE_ : Any = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE_ : Optional[int] = {v: k for k, v in idalabel.items()} return config def _A (__a , __a=False ) -> Any: """simple docstring""" for i in range(1 , 6 ): if f'layer_{i}.' in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace(f'layer_{i}.' , f'encoder.layer.{i - 1}.' ) if "conv_1." in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''conv_1.''' , '''conv_stem.''' ) if ".block." in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''.block.''' , '''.''' ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE_ : int = name.replace('''exp_1x1''' , '''expand_1x1''' ) if "red_1x1" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''red_1x1''' , '''reduce_1x1''' ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE_ : List[Any] = name.replace('''.local_rep.conv_3x3.''' , '''.conv_kxk.''' ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''.local_rep.conv_1x1.''' , '''.conv_1x1.''' ) if ".norm." in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''.norm.''' , '''.normalization.''' ) if ".conv." in name: SCREAMING_SNAKE_CASE_ : Optional[Any] = name.replace('''.conv.''' , '''.convolution.''' ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace('''.conv_proj.''' , '''.conv_projection.''' ) for i in range(0 , 2 ): for j in range(0 , 4 ): if f'.{i}.{j}.' in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace(f'.{i}.{j}.' , f'.{i}.layer.{j}.' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if f'.{i}.{j}.' in name: SCREAMING_SNAKE_CASE_ : str = name.replace(f'.{i}.{j}.' , f'.{i}.' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''expand_1x1''' , '''downsampling_layer.expand_1x1''' ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''conv_3x3''' , '''downsampling_layer.conv_3x3''' ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''reduce_1x1''' , '''downsampling_layer.reduce_1x1''' ) for i in range(2 , 5 ): if f'.global_rep.{i}.weight' in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace(f'.global_rep.{i}.weight' , '''.layernorm.weight''' ) if f'.global_rep.{i}.bias' in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace(f'.global_rep.{i}.bias' , '''.layernorm.bias''' ) if ".global_rep." in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''.global_rep.''' , '''.transformer.''' ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''.pre_norm_mha.0.''' , '''.layernorm_before.''' ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''.pre_norm_mha.1.out_proj.''' , '''.attention.output.dense.''' ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace('''.pre_norm_ffn.0.''' , '''.layernorm_after.''' ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace('''.pre_norm_ffn.1.''' , '''.intermediate.dense.''' ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''.pre_norm_ffn.4.''' , '''.output.dense.''' ) if ".transformer." in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''.transformer.''' , '''.transformer.layer.''' ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''.aspp_pool.''' , '''.''' ) if "seg_head." in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''seg_head.''' , '''segmentation_head.''' ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''segmentation_head.classifier.classifier.''' , '''segmentation_head.classifier.''' ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''classifier.fc.''' , '''classifier.''' ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE_ : str = '''mobilevit.''' + name return name def _A (__a , __a , __a=False ) -> Any: """simple docstring""" if base_model: SCREAMING_SNAKE_CASE_ : Optional[Any] = '''''' else: SCREAMING_SNAKE_CASE_ : Optional[int] = '''mobilevit.''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ : str = orig_state_dict.pop(__a ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE_ : str = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE_ : Tuple = key.split('''.''' ) SCREAMING_SNAKE_CASE_ : int = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE_ : Optional[int] = int(key_split[3] ) SCREAMING_SNAKE_CASE_ : Any = model.get_submodule(f'{model_prefix}encoder.layer.{layer_num}' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE_ : Dict = ( f'{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.' ) if "weight" in key: SCREAMING_SNAKE_CASE_ : str = val[:dim, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_ : int = val[-dim:, :] else: SCREAMING_SNAKE_CASE_ : int = val[:dim] SCREAMING_SNAKE_CASE_ : Tuple = val[dim : dim * 2] SCREAMING_SNAKE_CASE_ : List[str] = val[-dim:] else: SCREAMING_SNAKE_CASE_ : Tuple = val return orig_state_dict def _A () -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ : List[Any] = Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def _A (__a , __a , __a , __a=False ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = get_mobilevit_config(__a ) # load original state_dict SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.load(__a , map_location='''cpu''' ) # load 🤗 model if mobilevit_name.startswith('''deeplabv3_''' ): SCREAMING_SNAKE_CASE_ : Dict = MobileViTForSemanticSegmentation(__a ).eval() else: SCREAMING_SNAKE_CASE_ : str = MobileViTForImageClassification(__a ).eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = convert_state_dict(__a , __a ) model.load_state_dict(__a ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE_ : str = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE_ : Dict = image_processor(images=prepare_img() , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**__a ) SCREAMING_SNAKE_CASE_ : int = outputs.logits if mobilevit_name.startswith('''deeplabv3_''' ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor( [ [[6.20_65, 6.12_92, 6.20_70], [6.10_79, 6.12_54, 6.17_47], [6.00_42, 6.10_71, 6.10_34]], [[-6.92_53, -6.86_53, -7.03_98], [-7.32_18, -7.39_83, -7.36_70], [-7.19_61, -7.24_82, -7.15_69]], [[-4.47_23, -4.43_48, -4.37_69], [-5.36_29, -5.46_32, -5.45_98], [-5.15_87, -5.34_02, -5.50_59]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor( [ [[5.44_49, 5.57_33, 5.63_14], [5.18_15, 5.39_30, 5.59_63], [5.16_56, 5.43_33, 5.48_53]], [[-9.44_23, -9.77_66, -9.67_14], [-9.15_81, -9.57_20, -9.55_19], [-9.10_06, -9.64_58, -9.57_03]], [[-7.77_21, -7.37_16, -7.15_83], [-8.45_99, -8.06_24, -7.79_44], [-8.41_72, -7.83_66, -7.50_25]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE_ : str = torch.tensor( [ [[6.98_11, 6.97_43, 7.31_23], [7.17_77, 7.19_31, 7.39_38], [7.56_33, 7.80_50, 7.89_01]], [[-10.55_36, -10.23_32, -10.29_24], [-10.23_36, -9.86_24, -9.59_64], [-10.88_40, -10.81_58, -10.66_59]], [[-3.49_38, -3.06_31, -2.86_20], [-3.42_05, -2.81_35, -2.68_75], [-3.41_79, -2.79_45, -2.87_50]], ] ) else: raise ValueError(f'Unknown mobilevit_name: {mobilevit_name}' ) assert torch.allclose(logits[0, :3, :3, :3] , __a , atol=1e-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE_ : str = torch.tensor([-0.98_66, 0.23_92, -1.12_41] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE_ : str = torch.tensor([-2.47_61, -0.93_99, -1.95_87] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ) else: raise ValueError(f'Unknown mobilevit_name: {mobilevit_name}' ) assert torch.allclose(logits[0, :3] , __a , atol=1e-4 ) Path(__a ).mkdir(exist_ok=__a ) print(f'Saving model {mobilevit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__a ) if push_to_hub: SCREAMING_SNAKE_CASE_ : str = { '''mobilevit_s''': '''mobilevit-small''', '''mobilevit_xs''': '''mobilevit-x-small''', '''mobilevit_xxs''': '''mobilevit-xx-small''', '''deeplabv3_mobilevit_s''': '''deeplabv3-mobilevit-small''', '''deeplabv3_mobilevit_xs''': '''deeplabv3-mobilevit-x-small''', '''deeplabv3_mobilevit_xxs''': '''deeplabv3-mobilevit-xx-small''', } print('''Pushing to the hub...''' ) SCREAMING_SNAKE_CASE_ : Tuple = model_mapping[mobilevit_name] image_processor.push_to_hub(__a , organization='''apple''' ) model.push_to_hub(__a , organization='''apple''' ) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCAmelCase_ : List[Any] = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
318
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = data SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None def _A () -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ : List[Any] = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() SCREAMING_SNAKE_CASE_ : Union[str, Any] = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = q.get() SCREAMING_SNAKE_CASE_ : List[str] = f'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : Optional[int] = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : List[str] = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ : str = f'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : str = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : Any = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : int = right_node q.put(__a ) raise def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Tuple = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : str = [] while not q.empty(): SCREAMING_SNAKE_CASE_ : List[str] = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ : Tuple = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ : str = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Any = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.left SCREAMING_SNAKE_CASE_ : Any = stack.pop() print(n.data , end=''',''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = [], [] SCREAMING_SNAKE_CASE_ : List[Any] = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ : List[str] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def _A (__a = "" , __a=50 , __a="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = divmod(width - len(__a ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase_ : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
318
1
"""simple docstring""" import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : Tuple , lowercase_ : Dict=13 , lowercase_ : Tuple=7 , lowercase_ : Tuple=True , lowercase_ : List[str]=True , lowercase_ : List[str]=True , lowercase_ : List[str]=True , lowercase_ : str=99 , lowercase_ : Tuple=16 , lowercase_ : List[Any]=36 , lowercase_ : Optional[Any]=6 , lowercase_ : Union[str, Any]=6 , lowercase_ : List[str]=6 , lowercase_ : int=37 , lowercase_ : Dict="gelu" , lowercase_ : Tuple=0.1 , lowercase_ : str=0.1 , lowercase_ : Optional[Any]=512 , lowercase_ : Union[str, Any]=16 , lowercase_ : int=2 , lowercase_ : Optional[Any]=0.02 , lowercase_ : Tuple=3 , lowercase_ : Optional[Any]=4 , lowercase_ : List[str]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = parent SCREAMING_SNAKE_CASE_ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : int = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_input_mask SCREAMING_SNAKE_CASE_ : List[str] = use_token_type_ids SCREAMING_SNAKE_CASE_ : str = use_labels SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = embedding_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_groups SCREAMING_SNAKE_CASE_ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : int = max_position_embeddings SCREAMING_SNAKE_CASE_ : Any = type_vocab_size SCREAMING_SNAKE_CASE_ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : str = num_choices SCREAMING_SNAKE_CASE_ : int = scope def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE_ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : List[Any] = None SCREAMING_SNAKE_CASE_ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE_ : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Optional[int] , lowercase_ : Dict , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AlbertModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : Any = model(lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = model(lowercase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size)) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Dict , lowercase_ : Any , lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = AlbertForPreTraining(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_ , sentence_order_label=lowercase_ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : int , lowercase_ : str , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = AlbertForMaskedLM(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : int , lowercase_ : List[str] , lowercase_ : Tuple , lowercase_ : str , lowercase_ : Optional[int] , lowercase_ : Any , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AlbertForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Optional[int] , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : Any , lowercase_ : List[str] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = AlbertForSequenceClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : str = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Dict , lowercase_ : int , lowercase_ : Dict , lowercase_ : str , lowercase_ : List[str] , lowercase_ : Any , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : str = AlbertForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : str , lowercase_ : Dict , lowercase_ : Any , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_choices SCREAMING_SNAKE_CASE_ : Optional[Any] = AlbertForMultipleChoice(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE_ : Dict = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE_ : int = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE_ : str = model( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : Dict = config_and_inputs SCREAMING_SNAKE_CASE_ : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = True def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[int]=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class in get_values(lowercase_): SCREAMING_SNAKE_CASE_ : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase_) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = AlbertModelTester(self) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Dict = AlbertModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = AlbertModel.from_pretrained('''albert-base-v2''') SCREAMING_SNAKE_CASE_ : str = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[str] = model(lowercase_ , attention_mask=lowercase_)[0] SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 11, 768)) self.assertEqual(output.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Any = torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowercase_ , atol=1e-4))
318
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = "ssube/stable-diffusion-x4-upscaler-onnx" def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any]=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, 3, 128, 128) , rng=random.Random(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Dict = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Tuple = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array( [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : List[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : int = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[int] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array( [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ort.SessionOptions() SCREAMING_SNAKE_CASE_ : Optional[int] = False return options def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Optional[int] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) SCREAMING_SNAKE_CASE_ : Tuple = LMSDiscreteScheduler.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , subfolder='''scheduler''') SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , scheduler=lowercase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : int = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=20 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Dict = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array( [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2
318
1
"""simple docstring""" def _A (__a , __a ) -> int: """simple docstring""" return int((input_a, input_a).count(0 ) != 0 ) def _A () -> None: """simple docstring""" assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
318
"""simple docstring""" from scipy.stats import pearsonr import datasets UpperCAmelCase_ : List[Any] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ UpperCAmelCase_ : Optional[int] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ UpperCAmelCase_ : Tuple = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float'''), '''references''': datasets.Value('''float'''), }) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=False): '''simple docstring''' if return_pvalue: SCREAMING_SNAKE_CASE_ : int = pearsonr(lowercase_ , lowercase_) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(lowercase_ , lowercase_)[0])}
318
1
"""simple docstring""" def _A (__a , __a ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(bin(__a ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(bin(__a ) )[2:] SCREAMING_SNAKE_CASE_ : Union[str, Any] = max(len(__a ) , len(__a ) ) return "0b" + "".join( str(int('''1''' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(__a ) , b_binary.zfill(__a ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
318
"""simple docstring""" import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class lowerCAmelCase__ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any , lowercase_ : Dict[str, int] , lowercase_ : List[str] , lowercase_ : int = None , lowercase_ : int = None): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE_ : str = pad_token_id SCREAMING_SNAKE_CASE_ : Optional[int] = max_length SCREAMING_SNAKE_CASE_ : Dict = vocab SCREAMING_SNAKE_CASE_ : Dict = merges SCREAMING_SNAKE_CASE_ : Union[str, Any] = BytePairTokenizer(lowercase_ , lowercase_ , sequence_length=lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : GPTaTokenizer , *lowercase_ : Optional[Any] , **lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = [''' '''.join(lowercase_) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE_ : str = tokenizer.get_vocab() return cls(lowercase_ , lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowercase_ : Union[str, os.PathLike] , *lowercase_ : List[str] , **lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = GPTaTokenizer.from_pretrained(lowercase_ , *lowercase_ , **lowercase_) return cls.from_tokenizer(lowercase_ , *lowercase_ , **lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict , lowercase_ : List[Any]): '''simple docstring''' return cls(**lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[Any] , lowercase_ : int = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.tf_tokenizer(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.ones_like(lowercase_) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = pad_model_inputs( lowercase_ , max_seq_length=lowercase_ , pad_value=self.pad_token_id) return {"attention_mask": attention_mask, "input_ids": input_ids}
318
1
"""simple docstring""" UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : Dict = { 0: """Sunday""", 1: """Monday""", 2: """Tuesday""", 3: """Wednesday""", 4: """Thursday""", 5: """Friday""", 6: """Saturday""", } def _A (__a , __a , __a ) -> str: """simple docstring""" assert len(str(__a ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: SCREAMING_SNAKE_CASE_ : Tuple = year // 1_00 SCREAMING_SNAKE_CASE_ : List[str] = (5 * (century % 4) + 2) % 7 SCREAMING_SNAKE_CASE_ : List[Any] = year % 1_00 SCREAMING_SNAKE_CASE_ : List[str] = centurian % 12 SCREAMING_SNAKE_CASE_ : Any = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 SCREAMING_SNAKE_CASE_ : List[Any] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) SCREAMING_SNAKE_CASE_ : str = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
318
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file''']) with open(self.vocab_file , '''w''' , encoding='''utf-8''') as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens])) SCREAMING_SNAKE_CASE_ : Dict = { '''do_resize''': True, '''size''': {'''height''': 224, '''width''': 224}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], '''do_convert_rgb''': True, } SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname , lowercase_) with open(self.image_processor_file , '''w''' , encoding='''utf-8''') as fp: json.dump(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , **lowercase_ : str): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple , **lowercase_ : List[Any]): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , **lowercase_ : str): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' shutil.rmtree(self.tmpdirname) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] SCREAMING_SNAKE_CASE_ : Dict = [Image.fromarray(np.moveaxis(lowercase_ , 0 , -1)) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_slow.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase_) SCREAMING_SNAKE_CASE_ : Any = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) processor_fast.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , lowercase_) self.assertIsInstance(processor_fast.tokenizer , lowercase_) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , lowercase_) self.assertIsInstance(processor_fast.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''') SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_image_processor(do_normalize=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=lowercase_) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , lowercase_) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Tuple = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Any = image_processor(lowercase_ , return_tensors='''np''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = processor(images=lowercase_ , return_tensors='''np''') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : str = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Optional[Any] = processor(text=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer(lowercase_) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : int = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : int = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']) # test if it raises when no input is passed with pytest.raises(lowercase_): processor() def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE_ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Optional[int] = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_ : Optional[int] = processor.batch_decode(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.batch_decode(lowercase_) self.assertListEqual(lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.get_image_processor() SCREAMING_SNAKE_CASE_ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE_ : Dict = ChineseCLIPProcessor(tokenizer=lowercase_ , image_processor=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE_ : Dict = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ : Dict = processor(text=lowercase_ , images=lowercase_) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
318
1
"""simple docstring""" UpperCAmelCase_ : int = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ UpperCAmelCase_ : Optional[Any] = [{"""type""": """code""", """content""": INSTALL_CONTENT}] UpperCAmelCase_ : Tuple = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
318
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "rwkv" __UpperCamelCase = {"max_position_embeddings": "context_length"} def __init__( self : Union[str, Any] , lowercase_ : Any=50277 , lowercase_ : str=1024 , lowercase_ : List[str]=4096 , lowercase_ : Optional[Any]=32 , lowercase_ : Any=None , lowercase_ : Any=None , lowercase_ : List[Any]=1e-5 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=0 , lowercase_ : int=6 , lowercase_ : Tuple=False , lowercase_ : Any=True , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Any = context_length SCREAMING_SNAKE_CASE_ : int = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size SCREAMING_SNAKE_CASE_ : int = intermediate_size if intermediate_size is not None else 4 * hidden_size SCREAMING_SNAKE_CASE_ : int = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : Optional[int] = rescale_every SCREAMING_SNAKE_CASE_ : Dict = use_cache SCREAMING_SNAKE_CASE_ : Dict = bos_token_id SCREAMING_SNAKE_CASE_ : Any = eos_token_id super().__init__( tie_word_embeddings=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_)
318
1
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.inf def set_batch_size(__a ) -> None: nonlocal batch_size if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__a , __a ) and feature.dtype == "binary": SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__a , __a ) return None if batch_size is np.inf else batch_size class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , lowercase_ : NestedDataStructureLike[PathLike] , lowercase_ : Optional[NamedSplit] = None , lowercase_ : Optional[Features] = None , lowercase_ : str = None , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : Optional[int] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , split=lowercase_ , features=lowercase_ , cache_dir=lowercase_ , keep_in_memory=lowercase_ , streaming=lowercase_ , num_proc=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = path_or_paths if isinstance(lowercase_ , lowercase_) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_ : Any = _PACKAGED_DATASETS_MODULES['''parquet'''][1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = Parquet( cache_dir=lowercase_ , data_files=lowercase_ , features=lowercase_ , hash=lowercase_ , **lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE_ : str = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None self.builder.download_and_prepare( download_config=lowercase_ , download_mode=lowercase_ , verification_mode=lowercase_ , base_path=lowercase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_ : Any = self.builder.as_dataset( split=self.split , verification_mode=lowercase_ , in_memory=self.keep_in_memory) return dataset class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Dataset , lowercase_ : Union[PathLike, BinaryIO] , lowercase_ : Optional[int] = None , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = dataset SCREAMING_SNAKE_CASE_ : Dict = path_or_buf SCREAMING_SNAKE_CASE_ : List[Any] = batch_size or get_writer_batch_size(dataset.features) SCREAMING_SNAKE_CASE_ : Any = parquet_writer_kwargs def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , '''wb+''') as buffer: SCREAMING_SNAKE_CASE_ : Optional[Any] = self._write(file_obj=lowercase_ , batch_size=lowercase_ , **self.parquet_writer_kwargs) else: SCREAMING_SNAKE_CASE_ : str = self._write(file_obj=self.path_or_buf , batch_size=lowercase_ , **self.parquet_writer_kwargs) return written def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : BinaryIO , lowercase_ : int , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = parquet_writer_kwargs.pop('''path_or_buf''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dataset.features.arrow_schema SCREAMING_SNAKE_CASE_ : Tuple = pq.ParquetWriter(lowercase_ , schema=lowercase_ , **lowercase_) for offset in logging.tqdm( range(0 , len(self.dataset) , lowercase_) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): SCREAMING_SNAKE_CASE_ : List[Any] = query_table( table=self.dataset._data , key=slice(lowercase_ , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(lowercase_) written += batch.nbytes writer.close() return written
318
"""simple docstring""" UpperCAmelCase_ : Optional[int] = 8.3_1_4_4_5_9_8 def _A (__a , __a ) -> float: """simple docstring""" if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example UpperCAmelCase_ : str = 300 UpperCAmelCase_ : str = 28 UpperCAmelCase_ : Any = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
318
1
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING UpperCAmelCase_ : List[str] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Dict , **lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(**lowercase_) requires_backends(self , '''vision''') requires_backends(self , '''torch''') if self.framework != "pt": raise ValueError(F'The {self.__class__} is only available in PyTorch.') self.check_model_type(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , **lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : List[str] = {} # preprocess args if "points_per_batch" in kwargs: SCREAMING_SNAKE_CASE_ : Any = kwargs['''points_per_batch'''] if "points_per_crop" in kwargs: SCREAMING_SNAKE_CASE_ : Dict = kwargs['''points_per_crop'''] if "crops_n_layers" in kwargs: SCREAMING_SNAKE_CASE_ : int = kwargs['''crops_n_layers'''] if "crop_overlap_ratio" in kwargs: SCREAMING_SNAKE_CASE_ : List[Any] = kwargs['''crop_overlap_ratio'''] if "crop_n_points_downscale_factor" in kwargs: SCREAMING_SNAKE_CASE_ : Tuple = kwargs['''crop_n_points_downscale_factor'''] # postprocess args if "pred_iou_thresh" in kwargs: SCREAMING_SNAKE_CASE_ : List[Any] = kwargs['''pred_iou_thresh'''] if "stability_score_offset" in kwargs: SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs['''stability_score_offset'''] if "mask_threshold" in kwargs: SCREAMING_SNAKE_CASE_ : Any = kwargs['''mask_threshold'''] if "stability_score_thresh" in kwargs: SCREAMING_SNAKE_CASE_ : Dict = kwargs['''stability_score_thresh'''] if "crops_nms_thresh" in kwargs: SCREAMING_SNAKE_CASE_ : Tuple = kwargs['''crops_nms_thresh'''] if "output_rle_mask" in kwargs: SCREAMING_SNAKE_CASE_ : int = kwargs['''output_rle_mask'''] if "output_bboxes_mask" in kwargs: SCREAMING_SNAKE_CASE_ : List[str] = kwargs['''output_bboxes_mask'''] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self : Optional[int] , lowercase_ : List[str] , *lowercase_ : Optional[int] , lowercase_ : Dict=None , lowercase_ : int=None , **lowercase_ : Union[str, Any]): '''simple docstring''' return super().__call__(lowercase_ , *lowercase_ , num_workers=lowercase_ , batch_size=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Tuple , lowercase_ : List[str]=64 , lowercase_ : int = 0 , lowercase_ : float = 512 / 1500 , lowercase_ : Optional[int] = 32 , lowercase_ : Optional[int] = 1 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = load_image(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor.size['''longest_edge'''] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor.generate_crop_boxes( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor(images=lowercase_ , return_tensors='''pt''') with self.device_placement(): if self.framework == "pt": SCREAMING_SNAKE_CASE_ : List[Any] = self.get_inference_context() with inference_context(): SCREAMING_SNAKE_CASE_ : int = self._ensure_tensor_on_device(lowercase_ , device=self.device) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model.get_image_embeddings(model_inputs.pop('''pixel_values''')) SCREAMING_SNAKE_CASE_ : Optional[Any] = image_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = grid_points.shape[1] SCREAMING_SNAKE_CASE_ : Any = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( '''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ''' '''To return all points at once, set points_per_batch to None''') for i in range(0 , lowercase_ , lowercase_): SCREAMING_SNAKE_CASE_ : str = grid_points[:, i : i + points_per_batch, :, :] SCREAMING_SNAKE_CASE_ : str = input_labels[:, i : i + points_per_batch] SCREAMING_SNAKE_CASE_ : List[Any] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : int=0.88 , lowercase_ : int=0.95 , lowercase_ : Dict=0 , lowercase_ : List[str]=1 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_inputs.pop('''input_boxes''') SCREAMING_SNAKE_CASE_ : Optional[int] = model_inputs.pop('''is_last''') SCREAMING_SNAKE_CASE_ : str = model_inputs.pop('''original_sizes''').tolist() SCREAMING_SNAKE_CASE_ : Optional[Any] = model_inputs.pop('''reshaped_input_sizes''').tolist() SCREAMING_SNAKE_CASE_ : int = self.model(**lowercase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks SCREAMING_SNAKE_CASE_ : Optional[Any] = model_outputs['''pred_masks'''] SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor.post_process_masks( lowercase_ , lowercase_ , lowercase_ , lowercase_ , binarize=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = model_outputs['''iou_scores'''] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Dict , lowercase_ : List[str]=False , lowercase_ : Union[str, Any]=False , lowercase_ : Dict=0.7 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [] SCREAMING_SNAKE_CASE_ : Optional[int] = [] SCREAMING_SNAKE_CASE_ : int = [] for model_output in model_outputs: all_scores.append(model_output.pop('''iou_scores''')) all_masks.extend(model_output.pop('''masks''')) all_boxes.append(model_output.pop('''boxes''')) SCREAMING_SNAKE_CASE_ : int = torch.cat(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat(lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.image_processor.post_process_for_mask_generation( lowercase_ , lowercase_ , lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = defaultdict(lowercase_) for output in model_outputs: for k, v in output.items(): extra[k].append(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} if output_rle_mask: SCREAMING_SNAKE_CASE_ : List[str] = rle_mask if output_bboxes_mask: SCREAMING_SNAKE_CASE_ : List[str] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
318
"""simple docstring""" import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList UpperCAmelCase_ : Union[str, Any] = ["""\nclass""", """\ndef""", """\n#""", """\n@""", """\nprint""", """\nif"""] class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : int=None , lowercase_ : Dict=1): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = dataset SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase_) if n_tasks is None else n_tasks SCREAMING_SNAKE_CASE_ : Optional[int] = n_copies def __iter__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for task in range(self.n_tasks): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip()) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowercase_ , padding=lowercase_ , return_tensors='''pt''') for task in range(self.n_tasks): for _ in range(self.n_copies): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = start_length SCREAMING_SNAKE_CASE_ : List[Any] = eof_strings SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer def __call__( self : Optional[int] , lowercase_ : Any , lowercase_ : int , **lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.tokenizer.batch_decode(input_ids[:, self.start_length :]) SCREAMING_SNAKE_CASE_ : Tuple = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings)) return all(lowercase_) def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.split('''(%s)''' % '''|'''.join(__a ) , __a ) # last string should be "" return "".join(string_list[:-2] ) def _A (__a , __a , __a , __a , __a , __a=20 , **__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = defaultdict(__a ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__a ) ): with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Optional[int] = batch['''ids'''].shape[-1] SCREAMING_SNAKE_CASE_ : Tuple = accelerator.unwrap_model(__a ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']] , num_return_sequences=__a , **__a ) # each task is generated batch_size times SCREAMING_SNAKE_CASE_ : List[Any] = batch['''task_id'''].repeat(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.pad_across_processes( __a , dim=1 , pad_index=tokenizer.pad_token_id ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) SCREAMING_SNAKE_CASE_ : int = generated_tokens.cpu().numpy() SCREAMING_SNAKE_CASE_ : Optional[Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__a , __a ): gen_token_dict[task].append(__a ) SCREAMING_SNAKE_CASE_ : int = [[] for _ in range(__a )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) code_gens[task].append(remove_last_block(__a ) ) return code_gens def _A () -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = HfArgumentParser(__a ) SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric SCREAMING_SNAKE_CASE_ : Any = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing SCREAMING_SNAKE_CASE_ : str = '''false''' if args.num_workers is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() set_seed(args.seed , device_specific=__a ) # Load model and tokenizer SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.eos_token SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings SCREAMING_SNAKE_CASE_ : List[str] = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0 , __a , __a )] ), } # Load evaluation dataset and metric SCREAMING_SNAKE_CASE_ : Optional[int] = load_dataset('''openai_humaneval''' ) SCREAMING_SNAKE_CASE_ : str = load_metric('''code_eval''' ) SCREAMING_SNAKE_CASE_ : int = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) SCREAMING_SNAKE_CASE_ : List[str] = args.n_samples // args.batch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = TokenizedDataset(__a , human_eval['''test'''] , n_copies=__a , n_tasks=__a ) # do not confuse args.batch_size, which is actually the num_return_sequences SCREAMING_SNAKE_CASE_ : Optional[int] = DataLoader(__a , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: SCREAMING_SNAKE_CASE_ : Any = code_eval_metric.compute(references=[''''''] , predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = accelerator.prepare(__a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = complete_code( __a , __a , __a , __a , n_tasks=__a , batch_size=args.batch_size , **__a , ) if accelerator.is_main_process: SCREAMING_SNAKE_CASE_ : int = [] for task in tqdm(range(__a ) ): SCREAMING_SNAKE_CASE_ : Tuple = human_eval['''test'''][task]['''test'''] SCREAMING_SNAKE_CASE_ : Tuple = f'check({human_eval["test"][task]["entry_point"]})' references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = code_eval_metric.compute( references=__a , predictions=__a , num_workers=args.num_workers ) print(f'Results: {pass_at_k}' ) # Save results to json file with open(args.output_file , '''w''' ) as fp: json.dump(__a , __a ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
318
1
"""simple docstring""" class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : Union[str, Any] , lowercase_ : int , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Optional[int] = graph self._normalize_graph(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = None def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Tuple , lowercase_ : str): '''simple docstring''' if sources is int: SCREAMING_SNAKE_CASE_ : str = [sources] if sinks is int: SCREAMING_SNAKE_CASE_ : Tuple = [sinks] if len(lowercase_) == 0 or len(lowercase_) == 0: return SCREAMING_SNAKE_CASE_ : int = sources[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = sinks[0] # make fake vertex if there are more # than one source or sink if len(lowercase_) > 1 or len(lowercase_) > 1: SCREAMING_SNAKE_CASE_ : Dict = 0 for i in sources: max_input_flow += sum(self.graph[i]) SCREAMING_SNAKE_CASE_ : int = len(self.graph) + 1 for room in self.graph: room.insert(0 , 0) self.graph.insert(0 , [0] * size) for i in sources: SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_input_flow SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : List[str] = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_input_flow SCREAMING_SNAKE_CASE_ : Tuple = size - 1 def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''') if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = algorithm(self) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[Any] , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = flow_network SCREAMING_SNAKE_CASE_ : Tuple = flow_network.verticesCount SCREAMING_SNAKE_CASE_ : Dict = flow_network.sourceIndex SCREAMING_SNAKE_CASE_ : Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that SCREAMING_SNAKE_CASE_ : Dict = flow_network.graph SCREAMING_SNAKE_CASE_ : Union[str, Any] = False def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' if not self.executed: self._algorithm() SCREAMING_SNAKE_CASE_ : Any = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' pass class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , lowercase_ : int): '''simple docstring''' super().__init__(lowercase_) # use this to save your result SCREAMING_SNAKE_CASE_ : Dict = -1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''') return self.maximum_flow class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , lowercase_ : Optional[int]): '''simple docstring''' super().__init__(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = [[0] * self.verticies_count for i in range(self.verticies_count)] SCREAMING_SNAKE_CASE_ : int = [0] * self.verticies_count SCREAMING_SNAKE_CASE_ : Union[str, Any] = [0] * self.verticies_count def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule SCREAMING_SNAKE_CASE_ : Optional[int] = [ i for i in range(self.verticies_count) if i != self.source_index and i != self.sink_index ] # move through list SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 while i < len(lowercase_): SCREAMING_SNAKE_CASE_ : Union[str, Any] = vertices_list[i] SCREAMING_SNAKE_CASE_ : Tuple = self.heights[vertex_index] self.process_vertex(lowercase_) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 else: i += 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = sum(self.preflow[self.source_index]) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : List[Any]): '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(lowercase_ , lowercase_) self.relabel(lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = None for to_index in range(self.verticies_count): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): SCREAMING_SNAKE_CASE_ : Optional[Any] = self.heights[to_index] if min_height is not None: SCREAMING_SNAKE_CASE_ : List[Any] = min_height + 1 if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = [0] UpperCAmelCase_ : str = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCAmelCase_ : List[str] = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCAmelCase_ : Optional[Any] = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCAmelCase_ : Optional[Any] = flow_network.find_maximum_flow() print(f'''maximum flow is {maximum_flow}''')
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "feature_extractor"] __UpperCamelCase = "TvltImageProcessor" __UpperCamelCase = "TvltFeatureExtractor" def __init__( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(image_processor=lowercase_ , feature_extractor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = feature_extractor def __call__( self : Any , lowercase_ : str=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : str=None , lowercase_ : int=False , lowercase_ : Union[str, Any]=False , *lowercase_ : List[Any] , **lowercase_ : List[str] , ): '''simple docstring''' if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''') SCREAMING_SNAKE_CASE_ : Any = None if images is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor(lowercase_ , mask_pixel=lowercase_ , *lowercase_ , **lowercase_) if images_mixed is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , is_mixed=lowercase_ , *lowercase_ , **lowercase_) if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor( lowercase_ , *lowercase_ , sampling_rate=lowercase_ , mask_audio=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {} if audio is not None: output_dict.update(lowercase_) if images is not None: output_dict.update(lowercase_) if images_mixed_dict is not None: output_dict.update(lowercase_) return output_dict @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
318
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase_ : int = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "facebook/nllb-200-distilled-600M" __UpperCamelCase = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) __UpperCamelCase = "translator" __UpperCamelCase = AutoTokenizer __UpperCamelCase = AutoModelForSeqaSeqLM __UpperCamelCase = LANGUAGE_CODES __UpperCamelCase = ["text", "text", "text"] __UpperCamelCase = ["text"] def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Dict , lowercase_ : str , lowercase_ : str): '''simple docstring''' if src_lang not in self.lang_to_code: raise ValueError(F'{src_lang} is not a supported language.') if tgt_lang not in self.lang_to_code: raise ValueError(F'{tgt_lang} is not a supported language.') SCREAMING_SNAKE_CASE_ : Any = self.lang_to_code[src_lang] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( lowercase_ , return_tensors='''pt''' , src_lang=lowercase_ , tgt_lang=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Any): '''simple docstring''' return self.model.generate(**lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : int): '''simple docstring''' return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=lowercase_)
318
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "SpeechT5FeatureExtractor" __UpperCamelCase = "SpeechT5Tokenizer" def __init__( self : Any , lowercase_ : Dict , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(lowercase_ , lowercase_) def __call__( self : List[Any] , *lowercase_ : List[Any] , **lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''audio''' , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.pop('''text''' , lowercase_) SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('''text_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''audio_target''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''sampling_rate''' , lowercase_) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''') if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''') if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''') if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor(lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) elif text is not None: SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : Any = None if audio_target is not None: SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extractor(audio_target=lowercase_ , *lowercase_ , sampling_rate=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = targets['''input_values'''] elif text_target is not None: SCREAMING_SNAKE_CASE_ : int = self.tokenizer(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : int = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = labels SCREAMING_SNAKE_CASE_ : Optional[Any] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Any = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowercase_ : Tuple , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('''input_values''' , lowercase_) SCREAMING_SNAKE_CASE_ : int = kwargs.pop('''input_ids''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''labels''' , lowercase_) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''') if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''') if input_values is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) elif input_ids is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.pad(lowercase_ , **lowercase_) else: SCREAMING_SNAKE_CASE_ : List[Any] = None if labels is not None: if "input_ids" in labels or (isinstance(lowercase_ , lowercase_) and "input_ids" in labels[0]): SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer.pad(lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : Dict = targets['''input_ids'''] else: SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.feature_size SCREAMING_SNAKE_CASE_ : Optional[int] = self.feature_extractor.num_mel_bins SCREAMING_SNAKE_CASE_ : str = self.feature_extractor.pad(lowercase_ , *lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : str = feature_size_hack SCREAMING_SNAKE_CASE_ : Dict = targets['''input_values'''] else: SCREAMING_SNAKE_CASE_ : List[Any] = None if inputs is None: return targets if targets is not None: SCREAMING_SNAKE_CASE_ : Dict = labels SCREAMING_SNAKE_CASE_ : List[str] = targets.get('''attention_mask''') if decoder_attention_mask is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowercase_ : Optional[int] , **lowercase_ : Tuple): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *lowercase_ : Dict , **lowercase_ : List[Any]): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_)
318
1
"""simple docstring""" def _A (__a , __a , __a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = len(__a ), len(grid[0] ) if ( min(__a , __a ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) SCREAMING_SNAKE_CASE_ : Dict = 0 count += depth_first_search(__a , row + 1 , __a , __a ) count += depth_first_search(__a , row - 1 , __a , __a ) count += depth_first_search(__a , __a , col + 1 , __a ) count += depth_first_search(__a , __a , col - 1 , __a ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
318
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _A (__a ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.inf def set_batch_size(__a ) -> None: nonlocal batch_size if isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__a , __a ) and feature.dtype == "binary": SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__a , __a ) return None if batch_size is np.inf else batch_size class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Any , lowercase_ : NestedDataStructureLike[PathLike] , lowercase_ : Optional[NamedSplit] = None , lowercase_ : Optional[Features] = None , lowercase_ : str = None , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : Optional[int] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , split=lowercase_ , features=lowercase_ , cache_dir=lowercase_ , keep_in_memory=lowercase_ , streaming=lowercase_ , num_proc=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = path_or_paths if isinstance(lowercase_ , lowercase_) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE_ : Any = _PACKAGED_DATASETS_MODULES['''parquet'''][1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = Parquet( cache_dir=lowercase_ , data_files=lowercase_ , features=lowercase_ , hash=lowercase_ , **lowercase_ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' if self.streaming: SCREAMING_SNAKE_CASE_ : str = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Optional[int] = None SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None self.builder.download_and_prepare( download_config=lowercase_ , download_mode=lowercase_ , verification_mode=lowercase_ , base_path=lowercase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE_ : Any = self.builder.as_dataset( split=self.split , verification_mode=lowercase_ , in_memory=self.keep_in_memory) return dataset class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Dataset , lowercase_ : Union[PathLike, BinaryIO] , lowercase_ : Optional[int] = None , **lowercase_ : Dict , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = dataset SCREAMING_SNAKE_CASE_ : Dict = path_or_buf SCREAMING_SNAKE_CASE_ : List[Any] = batch_size or get_writer_batch_size(dataset.features) SCREAMING_SNAKE_CASE_ : Any = parquet_writer_kwargs def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , '''wb+''') as buffer: SCREAMING_SNAKE_CASE_ : Optional[Any] = self._write(file_obj=lowercase_ , batch_size=lowercase_ , **self.parquet_writer_kwargs) else: SCREAMING_SNAKE_CASE_ : str = self._write(file_obj=self.path_or_buf , batch_size=lowercase_ , **self.parquet_writer_kwargs) return written def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : BinaryIO , lowercase_ : int , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = parquet_writer_kwargs.pop('''path_or_buf''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dataset.features.arrow_schema SCREAMING_SNAKE_CASE_ : Tuple = pq.ParquetWriter(lowercase_ , schema=lowercase_ , **lowercase_) for offset in logging.tqdm( range(0 , len(self.dataset) , lowercase_) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): SCREAMING_SNAKE_CASE_ : List[Any] = query_table( table=self.dataset._data , key=slice(lowercase_ , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(lowercase_) written += batch.nbytes writer.close() return written
318
1
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging UpperCAmelCase_ : Tuple = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = CLIPConfig __UpperCamelCase = ["CLIPEncoderLayer"] def __init__( self : str , lowercase_ : CLIPConfig): '''simple docstring''' super().__init__(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = CLIPVisionModelWithProjection(config.vision_config) SCREAMING_SNAKE_CASE_ : str = nn.Linear(config.vision_config.projection_dim , 1) SCREAMING_SNAKE_CASE_ : Optional[Any] = nn.Linear(config.vision_config.projection_dim , 1) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Dict , lowercase_ : Any , lowercase_ : Union[str, Any]=0.5 , lowercase_ : Optional[int]=0.5): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.vision_model(lowercase_)[0] SCREAMING_SNAKE_CASE_ : Any = self.p_head(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = nsfw_detected.flatten() SCREAMING_SNAKE_CASE_ : Union[str, Any] = nsfw_detected > p_threshold SCREAMING_SNAKE_CASE_ : int = nsfw_detected.tolist() if any(lowercase_): logger.warning( '''Potential NSFW content was detected in one or more images. A black image will be returned instead.''' ''' Try again with a different prompt and/or seed.''') for idx, nsfw_detected_ in enumerate(lowercase_): if nsfw_detected_: SCREAMING_SNAKE_CASE_ : Optional[int] = np.zeros(images[idx].shape) SCREAMING_SNAKE_CASE_ : List[str] = self.w_head(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = watermark_detected.flatten() SCREAMING_SNAKE_CASE_ : str = watermark_detected > w_threshold SCREAMING_SNAKE_CASE_ : Optional[int] = watermark_detected.tolist() if any(lowercase_): logger.warning( '''Potential watermarked content was detected in one or more images. A black image will be returned instead.''' ''' Try again with a different prompt and/or seed.''') for idx, watermark_detected_ in enumerate(lowercase_): if watermark_detected_: SCREAMING_SNAKE_CASE_ : Any = np.zeros(images[idx].shape) return images, nsfw_detected, watermark_detected
318
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Optional[Any] = ["""model.decoder.embed_positions.weights"""] def _A (__a ) -> Dict: """simple docstring""" if "emb" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def _A (__a , __a ) -> Tuple[Dict, Dict]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(state_dict.keys() ) SCREAMING_SNAKE_CASE_ : int = {} for key in keys: SCREAMING_SNAKE_CASE_ : int = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ : int = rename_keys(__a ) if "in_proj_weight" in key: # split fused qkv proj SCREAMING_SNAKE_CASE_ : List[str] = val[:hidden_size, :] SCREAMING_SNAKE_CASE_ : List[str] = val[hidden_size : 2 * hidden_size, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: SCREAMING_SNAKE_CASE_ : int = val else: SCREAMING_SNAKE_CASE_ : Any = val return state_dict, enc_dec_proj_state_dict def _A (__a ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values SCREAMING_SNAKE_CASE_ : Optional[int] = 10_24 SCREAMING_SNAKE_CASE_ : Tuple = 24 SCREAMING_SNAKE_CASE_ : Optional[Any] = 16 elif checkpoint == "medium": SCREAMING_SNAKE_CASE_ : List[str] = 15_36 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : Optional[int] = 24 elif checkpoint == "large": SCREAMING_SNAKE_CASE_ : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE_ : Optional[int] = 48 SCREAMING_SNAKE_CASE_ : int = 32 else: raise ValueError(f'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' ) SCREAMING_SNAKE_CASE_ : List[Any] = MusicgenDecoderConfig( hidden_size=__a , ffn_dim=hidden_size * 4 , num_hidden_layers=__a , num_attention_heads=__a , ) return config @torch.no_grad() def _A (__a , __a=None , __a=None , __a="cpu" ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = MusicGen.get_pretrained(__a , device=__a ) SCREAMING_SNAKE_CASE_ : Dict = decoder_config_from_checkpoint(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = fairseq_model.lm.state_dict() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = rename_state_dict( __a , hidden_size=decoder_config.hidden_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = TaEncoderModel.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : List[str] = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) SCREAMING_SNAKE_CASE_ : int = MusicgenForCausalLM(__a ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = decoder.load_state_dict(__a , strict=__a ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__a ) if len(__a ) > 0: raise ValueError(f'Missing key(s) in state_dict: {missing_keys}' ) if len(__a ) > 0: raise ValueError(f'Unexpected key(s) in state_dict: {unexpected_keys}' ) # init the composite model SCREAMING_SNAKE_CASE_ : str = MusicgenForConditionalGeneration(text_encoder=__a , audio_encoder=__a , decoder=__a ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__a ) # check we can do a forward pass SCREAMING_SNAKE_CASE_ : Dict = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=__a , decoder_input_ids=__a ).logits if logits.shape != (8, 1, 20_48): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor SCREAMING_SNAKE_CASE_ : str = AutoTokenizer.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ : str = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) SCREAMING_SNAKE_CASE_ : Tuple = MusicgenProcessor(feature_extractor=__a , tokenizer=__a ) # set the appropriate bos/pad token ids SCREAMING_SNAKE_CASE_ : str = 20_48 SCREAMING_SNAKE_CASE_ : List[Any] = 20_48 # set other default generation config params SCREAMING_SNAKE_CASE_ : int = int(30 * audio_encoder.config.frame_rate ) SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : Optional[Any] = 3.0 if pytorch_dump_folder is not None: Path(__a ).mkdir(exist_ok=__a ) logger.info(f'Saving model {checkpoint} to {pytorch_dump_folder}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if repo_id: logger.info(f'Pushing model {checkpoint} to {repo_id}' ) model.push_to_hub(__a ) processor.push_to_hub(__a ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) UpperCAmelCase_ : Dict = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
318
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : str , lowercase_ : Optional[Any]=13 , lowercase_ : Tuple=7 , lowercase_ : List[Any]=True , lowercase_ : List[str]=True , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : int=99 , lowercase_ : str=32 , lowercase_ : str=2 , lowercase_ : Union[str, Any]=4 , lowercase_ : List[Any]=37 , lowercase_ : Optional[Any]="gelu" , lowercase_ : Any=0.1 , lowercase_ : Union[str, Any]=0.1 , lowercase_ : Tuple=512 , lowercase_ : Optional[Any]=16 , lowercase_ : List[str]=2 , lowercase_ : Union[str, Any]=0.02 , lowercase_ : Any=3 , lowercase_ : Dict=4 , lowercase_ : Tuple=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = parent SCREAMING_SNAKE_CASE_ : str = 13 SCREAMING_SNAKE_CASE_ : Dict = 7 SCREAMING_SNAKE_CASE_ : List[str] = True SCREAMING_SNAKE_CASE_ : int = True SCREAMING_SNAKE_CASE_ : Dict = True SCREAMING_SNAKE_CASE_ : Any = True SCREAMING_SNAKE_CASE_ : Union[str, Any] = 99 SCREAMING_SNAKE_CASE_ : str = 32 SCREAMING_SNAKE_CASE_ : Optional[int] = 2 SCREAMING_SNAKE_CASE_ : int = 4 SCREAMING_SNAKE_CASE_ : Dict = 37 SCREAMING_SNAKE_CASE_ : List[str] = '''gelu''' SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 SCREAMING_SNAKE_CASE_ : Tuple = 0.1 SCREAMING_SNAKE_CASE_ : str = 512 SCREAMING_SNAKE_CASE_ : str = 16 SCREAMING_SNAKE_CASE_ : Optional[int] = 2 SCREAMING_SNAKE_CASE_ : Optional[int] = 0.02 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE_ : List[str] = 4 SCREAMING_SNAKE_CASE_ : Optional[int] = None def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : int = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE_ : Union[str, Any] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=lowercase_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : str , lowercase_ : str , lowercase_ : List[Any] , lowercase_ : Dict , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TFRoFormerModel(config=lowercase_) SCREAMING_SNAKE_CASE_ : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} SCREAMING_SNAKE_CASE_ : List[Any] = [input_ids, input_mask] SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = model(lowercase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : List[Any] , lowercase_ : int , lowercase_ : Any , lowercase_ : List[str] , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : str = TFRoFormerForCausalLM(config=lowercase_) SCREAMING_SNAKE_CASE_ : int = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_)['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape) , [self.batch_size, self.seq_length, self.vocab_size]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Any , lowercase_ : Union[str, Any] , lowercase_ : Tuple , lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFRoFormerForMaskedLM(config=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : List[str] = TFRoFormerForSequenceClassification(config=lowercase_) SCREAMING_SNAKE_CASE_ : Any = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : str , lowercase_ : str , lowercase_ : Dict , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : List[str] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.num_choices SCREAMING_SNAKE_CASE_ : Dict = TFRoFormerForMultipleChoice(config=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.tile(tf.expand_dims(lowercase_ , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.tile(tf.expand_dims(lowercase_ , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE_ : Tuple = tf.tile(tf.expand_dims(lowercase_ , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[Any] , lowercase_ : List[str] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Tuple = TFRoFormerForTokenClassification(config=lowercase_) SCREAMING_SNAKE_CASE_ : Any = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : str = model(lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[int] , lowercase_ : List[Any] , lowercase_ : Dict , lowercase_ : int , lowercase_ : str , lowercase_ : str , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = TFRoFormerForQuestionAnswering(config=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } SCREAMING_SNAKE_CASE_ : Any = model(lowercase_) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) __UpperCamelCase = ( { "feature-extraction": TFRoFormerModel, "fill-mask": TFRoFormerForMaskedLM, "question-answering": TFRoFormerForQuestionAnswering, "text-classification": TFRoFormerForSequenceClassification, "text-generation": TFRoFormerForCausalLM, "token-classification": TFRoFormerForTokenClassification, "zero-shot": TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : int , lowercase_ : Any , lowercase_ : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = TFRoFormerModelTester(self) SCREAMING_SNAKE_CASE_ : Tuple = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''') self.assertIsNotNone(lowercase_) @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''') SCREAMING_SNAKE_CASE_ : Optional[int] = tf.constant([[0, 1, 2, 3, 4, 5]]) SCREAMING_SNAKE_CASE_ : Any = model(lowercase_)[0] # TODO Replace vocab size SCREAMING_SNAKE_CASE_ : List[str] = 50000 SCREAMING_SNAKE_CASE_ : Dict = [1, 6, vocab_size] self.assertEqual(output.shape , lowercase_) print(output[:, :3, :3]) # TODO Replace values below with what was printed above. SCREAMING_SNAKE_CASE_ : Tuple = tf.constant( [ [ [-0.12_05_33_41, -1.0_26_49_01, 0.29_22_19_46], [-1.5_13_37_83, 0.19_74_33, 0.15_19_06_07], [-5.0_13_54_03, -3.90_02_56, -0.84_03_87_64], ] ]) tf.debugging.assert_near(output[:, :3, :3] , lowercase_ , atol=1e-4) @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = 1e-4 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = tf.constant([[4, 10]]) SCREAMING_SNAKE_CASE_ : Tuple = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6) SCREAMING_SNAKE_CASE_ : Union[str, Any] = emba(input_ids.shape) SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.constant( [[0.00_00, 0.00_00, 0.00_00, 1.00_00, 1.00_00, 1.00_00], [0.84_15, 0.04_64, 0.00_22, 0.54_03, 0.99_89, 1.00_00]]) tf.debugging.assert_near(lowercase_ , lowercase_ , atol=self.tolerance) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = tf.constant( [ [0.00_00, 0.00_00, 0.00_00, 0.00_00, 0.00_00], [0.84_15, 0.82_19, 0.80_20, 0.78_19, 0.76_17], [0.90_93, 0.93_64, 0.95_81, 0.97_49, 0.98_70], ]) SCREAMING_SNAKE_CASE_ : int = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512) emba([2, 16, 512]) SCREAMING_SNAKE_CASE_ : Any = emba.weight[:3, :5] tf.debugging.assert_near(lowercase_ , lowercase_ , atol=self.tolerance) @require_tf class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = 1e-4 def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa) , shape=(2, 12, 16, 64)) / 100 SCREAMING_SNAKE_CASE_ : List[Any] = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa) , shape=(2, 12, 16, 64)) / 100 SCREAMING_SNAKE_CASE_ : Any = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64) SCREAMING_SNAKE_CASE_ : str = embed_positions([2, 16, 768])[None, None, :, :] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = TFRoFormerSelfAttention.apply_rotary_position_embeddings( lowercase_ , lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = tf.constant( [ [0.00_00, 0.01_00, 0.02_00, 0.03_00, 0.04_00, 0.05_00, 0.06_00, 0.07_00], [-0.20_12, 0.88_97, 0.02_63, 0.94_01, 0.20_74, 0.94_63, 0.34_81, 0.93_43], [-1.70_57, 0.62_71, -1.21_45, 1.38_97, -0.63_03, 1.76_47, -0.11_73, 1.89_85], [-2.17_31, -1.63_97, -2.73_58, 0.28_54, -2.18_40, 1.71_83, -1.30_18, 2.48_71], [0.27_17, -3.61_73, -2.92_06, -2.19_88, -3.66_38, 0.38_58, -2.91_55, 2.29_80], [3.98_59, -2.15_80, -0.79_84, -4.49_04, -4.11_81, -2.02_52, -4.47_82, 1.12_53], ]) SCREAMING_SNAKE_CASE_ : Any = tf.constant( [ [0.00_00, -0.01_00, -0.02_00, -0.03_00, -0.04_00, -0.05_00, -0.06_00, -0.07_00], [0.20_12, -0.88_97, -0.02_63, -0.94_01, -0.20_74, -0.94_63, -0.34_81, -0.93_43], [1.70_57, -0.62_71, 1.21_45, -1.38_97, 0.63_03, -1.76_47, 0.11_73, -1.89_85], [2.17_31, 1.63_97, 2.73_58, -0.28_54, 2.18_40, -1.71_83, 1.30_18, -2.48_71], [-0.27_17, 3.61_73, 2.92_06, 2.19_88, 3.66_38, -0.38_58, 2.91_55, -2.29_80], [-3.98_59, 2.15_80, 0.79_84, 4.49_04, 4.11_81, 2.02_52, 4.47_82, -1.12_53], ]) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , lowercase_ , atol=self.tolerance) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , lowercase_ , atol=self.tolerance)
318
"""simple docstring""" from pathlib import Path import numpy as np from PIL import Image def _A (__a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def _A (__a ) -> np.ndarray: """simple docstring""" return (gray > 1_27) & (gray <= 2_55) def _A (__a , __a ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = np.zeros_like(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE_ : Union[str, Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE_ : Optional[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE_ : Any = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCAmelCase_ : Dict = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" UpperCAmelCase_ : List[Any] = np.array(Image.open(lena_path)) # kernel to be applied UpperCAmelCase_ : Any = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCAmelCase_ : Tuple = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCAmelCase_ : List[str] = Image.fromarray(output).convert("""RGB""") pil_img.save("""result_dilation.png""")
318
1
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any]=99 , lowercase_ : Optional[Any]=13 , lowercase_ : List[str]=16 , lowercase_ : Any=7 , lowercase_ : Tuple=True , lowercase_ : Optional[Any]=True , lowercase_ : Tuple=True , lowercase_ : List[Any]=False , lowercase_ : List[str]=True , lowercase_ : Union[str, Any]=2 , lowercase_ : Union[str, Any]=32 , lowercase_ : int=4 , lowercase_ : Any=4 , lowercase_ : Any=30 , lowercase_ : int=0 , lowercase_ : str=1 , lowercase_ : str=2 , lowercase_ : Tuple=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE_ : int = self.decoder_seq_length SCREAMING_SNAKE_CASE_ : Tuple = is_training SCREAMING_SNAKE_CASE_ : Any = use_attention_mask SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = d_model SCREAMING_SNAKE_CASE_ : List[str] = d_model SCREAMING_SNAKE_CASE_ : int = decoder_layers SCREAMING_SNAKE_CASE_ : Optional[Any] = decoder_layers SCREAMING_SNAKE_CASE_ : List[str] = decoder_ffn_dim SCREAMING_SNAKE_CASE_ : List[Any] = decoder_attention_heads SCREAMING_SNAKE_CASE_ : Union[str, Any] = decoder_attention_heads SCREAMING_SNAKE_CASE_ : str = eos_token_id SCREAMING_SNAKE_CASE_ : int = bos_token_id SCREAMING_SNAKE_CASE_ : Dict = pad_token_id SCREAMING_SNAKE_CASE_ : Tuple = decoder_start_token_id SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : List[Any] = decoder_seq_length SCREAMING_SNAKE_CASE_ : Any = 2 SCREAMING_SNAKE_CASE_ : Optional[int] = 1 def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : str = None if self.use_attention_mask: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Any = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Tuple = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Union[str, Any] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : List[Any] = TrOCRDecoder(config=lowercase_).to(lowercase_).eval() SCREAMING_SNAKE_CASE_ : Dict = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , use_cache=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = model(lowercase_ , use_cache=lowercase_) self.parent.assertTrue(len(lowercase_) == len(lowercase_)) self.parent.assertTrue(len(lowercase_) == len(lowercase_) + 1) SCREAMING_SNAKE_CASE_ : List[str] = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor((2, 1) , config.vocab_size - 1) + 1 # append to next input_ids and SCREAMING_SNAKE_CASE_ : Dict = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_)['''last_hidden_state'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , past_key_values=lowercase_)['''last_hidden_state'''] # select random slice SCREAMING_SNAKE_CASE_ : Any = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE_ : List[str] = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() SCREAMING_SNAKE_CASE_ : Optional[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(lowercase_ , lowercase_ , atol=1e-3) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = config_and_inputs SCREAMING_SNAKE_CASE_ : List[str] = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () __UpperCamelCase = (TrOCRForCausalLM,) if is_torch_available() else () __UpperCamelCase = {"text-generation": TrOCRForCausalLM} if is_torch_available() else {} __UpperCamelCase = True __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = TrOCRStandaloneDecoderModelTester(self , is_training=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = ConfigTester(self , config_class=lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''') # and it's not used enough to be worth fixing :) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass
318
"""simple docstring""" from collections import defaultdict def _A (__a , __a ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = first_str.lower().strip() SCREAMING_SNAKE_CASE_ : List[Any] = second_str.lower().strip() # Remove whitespace SCREAMING_SNAKE_CASE_ : Dict = first_str.replace(''' ''' , '''''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = second_str.replace(''' ''' , '''''' ) # Strings of different lengths are not anagrams if len(__a ) != len(__a ): return False # Default values for count should be 0 SCREAMING_SNAKE_CASE_ : defaultdict[str, int] = defaultdict(__a ) # For each character in input strings, # increment count in the corresponding for i in range(len(__a ) ): 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() UpperCAmelCase_ : Any = input("""Enter the first string """).strip() UpperCAmelCase_ : Optional[int] = input("""Enter the second string """).strip() UpperCAmelCase_ : Union[str, Any] = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {'' if status else 'not '}anagrams.''')
318
1
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) UpperCAmelCase_ : List[Any] = [ """cross_validation.py""", """gradient_accumulation.py""", """local_sgd.py""", """multi_process_metrics.py""", """memory.py""", """automatic_gradient_accumulation.py""", """fsdp_with_peak_mem_tracking.py""", """deepspeed_with_config_support.py""", """megatron_lm_gpt_pretraining.py""", ] class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : bool , lowercase_ : str = None , lowercase_ : list = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : List[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''')) SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.abspath('''examples''') for item in os.listdir(lowercase_): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.join(lowercase_ , lowercase_) if os.path.isfile(lowercase_) and ".py" in item_path: with self.subTest( tested_script=lowercase_ , feature_script=lowercase_ , tested_section='''main()''' if parser_only else '''training_function()''' , ): SCREAMING_SNAKE_CASE_ : Dict = compare_against_test( os.path.join(lowercase_ , lowercase_) , lowercase_ , lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = '''\n'''.join(lowercase_) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE_ : Dict = diff.replace(lowercase_ , '''''') self.assertEqual(lowercase_ , '''''') def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' self.one_complete_example('''complete_nlp_example.py''' , lowercase_) self.one_complete_example('''complete_nlp_example.py''' , lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''')) SCREAMING_SNAKE_CASE_ : int = [ ''' ''' * 16 + '''{\n\n''', ''' ''' * 20 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 20 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 20 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 20 + '''"epoch": epoch,\n\n''', ''' ''' * 16 + '''},\n\n''', ''' ''' * 16 + '''step=epoch,\n''', ''' ''' * 12, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , lowercase_ , lowercase_ , lowercase_) self.one_complete_example('''complete_cv_example.py''' , lowercase_ , lowercase_ , lowercase_) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = False @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple): '''simple docstring''' super().setUpClass() SCREAMING_SNAKE_CASE_ : str = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(cls._tmpdir , '''default_config.yml''') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE_ : Any = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def _SCREAMING_SNAKE_CASE ( cls : str): '''simple docstring''' super().tearDownClass() shutil.rmtree(cls._tmpdir) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = F'\n examples/by_feature/checkpointing.py\n --checkpointing_steps epoch\n --output_dir {self.tmpdir}\n '.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0'''))) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = F'\n examples/by_feature/checkpointing.py\n --checkpointing_steps 1\n --output_dir {self.tmpdir}\n '.split() SCREAMING_SNAKE_CASE_ : List[str] = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2'''))) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = F'\n examples/by_feature/checkpointing.py\n --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0")}\n '.split() SCREAMING_SNAKE_CASE_ : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=lowercase_) self.assertNotIn('''epoch 0:''' , lowercase_) self.assertIn('''epoch 1:''' , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = F'\n examples/by_feature/checkpointing.py\n --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2")}\n '.split() SCREAMING_SNAKE_CASE_ : str = run_command(self._launch_args + testargs , return_stdout=lowercase_) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE_ : Any = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , lowercase_) self.assertIn('''epoch 1:''' , lowercase_) else: self.assertIn('''epoch 0:''' , lowercase_) self.assertIn('''epoch 1:''' , lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''}): SCREAMING_SNAKE_CASE_ : Tuple = run_command(self._launch_args + testargs , return_stdout=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = re.findall('''({.+})''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = [r for r in results if '''accuracy''' in r][-1] SCREAMING_SNAKE_CASE_ : Dict = ast.literal_eval(lowercase_) self.assertGreaterEqual(results['''accuracy'''] , 0.75) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''}) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE_ : Tuple = F'\n examples/by_feature/tracking.py\n --with_tracking\n --project_dir {tmpdir}\n '.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(lowercase_ , '''tracking'''))) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs)
318
"""simple docstring""" import argparse from collections import defaultdict import yaml UpperCAmelCase_ : Optional[Any] = """docs/source/en/_toctree.yml""" def _A (__a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 SCREAMING_SNAKE_CASE_ : List[Any] = [key for key, value in counts.items() if value > 1] SCREAMING_SNAKE_CASE_ : int = [] for duplicate_key in duplicates: SCREAMING_SNAKE_CASE_ : List[str] = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'{duplicate_key} is present several times in the documentation table of content at ' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] ) # Sort return sorted(__a , key=lambda __a : s["title"].lower() ) def _A (__a=False ) -> Tuple: """simple docstring""" with open(__a , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE_ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE_ : str = content[api_idx]['''sections'''] # Then to the model doc SCREAMING_SNAKE_CASE_ : List[Any] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = api_doc[model_idx]['''sections'''] SCREAMING_SNAKE_CASE_ : str = [(idx, section) for idx, section in enumerate(__a ) if '''sections''' in section] SCREAMING_SNAKE_CASE_ : Optional[Any] = False for idx, modality_doc in modalities_docs: SCREAMING_SNAKE_CASE_ : List[str] = modality_doc['''sections'''] SCREAMING_SNAKE_CASE_ : Union[str, Any] = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: SCREAMING_SNAKE_CASE_ : str = True if overwrite: SCREAMING_SNAKE_CASE_ : Optional[int] = new_modality_doc if diff: if overwrite: SCREAMING_SNAKE_CASE_ : List[Any] = model_doc SCREAMING_SNAKE_CASE_ : int = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) 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__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Tuple = parser.parse_args() check_model_doc(args.fix_and_overwrite)
318
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = { """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "pegasus" __UpperCamelCase = ["past_key_values"] __UpperCamelCase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Union[str, Any] , lowercase_ : Any=50265 , lowercase_ : Union[str, Any]=1024 , lowercase_ : Any=12 , lowercase_ : Optional[Any]=4096 , lowercase_ : Tuple=16 , lowercase_ : Dict=12 , lowercase_ : List[str]=4096 , lowercase_ : int=16 , lowercase_ : List[Any]=0.0 , lowercase_ : str=0.0 , lowercase_ : Tuple=True , lowercase_ : List[str]=True , lowercase_ : int="gelu" , lowercase_ : Dict=1024 , lowercase_ : str=0.1 , lowercase_ : str=0.0 , lowercase_ : Optional[Any]=0.0 , lowercase_ : List[str]=0.02 , lowercase_ : Optional[Any]=0 , lowercase_ : Union[str, Any]=False , lowercase_ : Dict=0 , lowercase_ : str=1 , lowercase_ : Tuple=1 , **lowercase_ : Union[str, Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = vocab_size SCREAMING_SNAKE_CASE_ : str = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE_ : int = encoder_ffn_dim SCREAMING_SNAKE_CASE_ : List[str] = encoder_layers SCREAMING_SNAKE_CASE_ : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE_ : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE_ : List[str] = decoder_layers SCREAMING_SNAKE_CASE_ : List[str] = decoder_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = dropout SCREAMING_SNAKE_CASE_ : Dict = attention_dropout SCREAMING_SNAKE_CASE_ : Tuple = activation_dropout SCREAMING_SNAKE_CASE_ : Dict = activation_function SCREAMING_SNAKE_CASE_ : Dict = init_std SCREAMING_SNAKE_CASE_ : List[str] = encoder_layerdrop SCREAMING_SNAKE_CASE_ : List[Any] = decoder_layerdrop SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = encoder_layers SCREAMING_SNAKE_CASE_ : Optional[Any] = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowercase_ , eos_token_id=lowercase_ , is_encoder_decoder=lowercase_ , decoder_start_token_id=lowercase_ , forced_eos_token_id=lowercase_ , **lowercase_ , ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return self.encoder_attention_heads @property def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return self.d_model
318
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) UpperCAmelCase_ : int = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "ctrl" __UpperCamelCase = ["past_key_values"] __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[Any] , lowercase_ : List[Any]=246534 , lowercase_ : List[str]=256 , lowercase_ : int=1280 , lowercase_ : int=8192 , lowercase_ : Any=48 , lowercase_ : Dict=16 , lowercase_ : Tuple=0.1 , lowercase_ : Union[str, Any]=0.1 , lowercase_ : Tuple=1e-6 , lowercase_ : Any=0.02 , lowercase_ : Dict=True , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE_ : str = n_positions SCREAMING_SNAKE_CASE_ : List[Any] = n_embd SCREAMING_SNAKE_CASE_ : Optional[Any] = n_layer SCREAMING_SNAKE_CASE_ : Dict = n_head SCREAMING_SNAKE_CASE_ : Any = dff SCREAMING_SNAKE_CASE_ : Optional[int] = resid_pdrop SCREAMING_SNAKE_CASE_ : Dict = embd_pdrop SCREAMING_SNAKE_CASE_ : Any = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : Dict = initializer_range SCREAMING_SNAKE_CASE_ : Union[str, Any] = use_cache super().__init__(**lowercase_)
318
"""simple docstring""" from __future__ import annotations UpperCAmelCase_ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase_ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase_ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _A (__a , __a , __a , __a ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _A (__a ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _A (__a ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__a ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__a , __a , __a , __a ): SCREAMING_SNAKE_CASE_ : Tuple = digit if sudoku(__a ) is not None: return grid SCREAMING_SNAKE_CASE_ : Any = 0 return None def _A (__a ) -> None: """simple docstring""" for row in grid: for cell in row: print(__a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("""\nExample grid:\n""" + """=""" * 20) print_solution(example_grid) print("""\nExample grid solution:""") UpperCAmelCase_ : str = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("""Cannot find a solution.""")
318
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Union[str, Any] = { """configuration_blenderbot""": [ """BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotConfig""", """BlenderbotOnnxConfig""", ], """tokenization_blenderbot""": ["""BlenderbotTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = ["""BlenderbotTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = [ """BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotForCausalLM""", """BlenderbotForConditionalGeneration""", """BlenderbotModel""", """BlenderbotPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : str = [ """TFBlenderbotForConditionalGeneration""", """TFBlenderbotModel""", """TFBlenderbotPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = [ """FlaxBlenderbotForConditionalGeneration""", """FlaxBlenderbotModel""", """FlaxBlenderbotPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
318
"""simple docstring""" from itertools import permutations def _A (__a ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False SCREAMING_SNAKE_CASE_ : List[str] = [7, 11, 13, 17] for i, test in enumerate(__a ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def _A (__a = 10 ) -> int: """simple docstring""" return sum( int(''''''.join(map(__a , __a ) ) ) for num in permutations(range(__a ) ) if is_substring_divisible(__a ) ) if __name__ == "__main__": print(f'''{solution() = }''')
318
1
"""simple docstring""" def _A (__a = 10 , __a = 10_00 , __a = True ) -> int: """simple docstring""" assert ( isinstance(__a , __a ) and isinstance(__a , __a ) and isinstance(__a , __a ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('''Invalid value for min_val or max_val (min_value < max_value)''' ) return min_val if option else max_val def _A (__a , __a ) -> int: """simple docstring""" return int((number_a + number_a) / 2 ) def _A (__a , __a , __a ) -> None: """simple docstring""" assert ( isinstance(__a , __a ) and isinstance(__a , __a ) and isinstance(__a , __a ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('''argument value for lower and higher must be(lower > higher)''' ) if not lower < to_guess < higher: raise ValueError( '''guess value must be within the range of lower and higher value''' ) def answer(__a ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('''started...''' ) SCREAMING_SNAKE_CASE_ : Any = lower SCREAMING_SNAKE_CASE_ : str = higher SCREAMING_SNAKE_CASE_ : List[str] = [] while True: SCREAMING_SNAKE_CASE_ : int = get_avg(__a , __a ) last_numbers.append(__a ) if answer(__a ) == "low": SCREAMING_SNAKE_CASE_ : Optional[int] = number elif answer(__a ) == "high": SCREAMING_SNAKE_CASE_ : List[str] = number else: break print(f'guess the number : {last_numbers[-1]}' ) print(f'details : {last_numbers!s}' ) def _A () -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = int(input('''Enter lower value : ''' ).strip() ) SCREAMING_SNAKE_CASE_ : str = int(input('''Enter high value : ''' ).strip() ) SCREAMING_SNAKE_CASE_ : Optional[Any] = int(input('''Enter value to guess : ''' ).strip() ) guess_the_number(__a , __a , __a ) if __name__ == "__main__": main()
318
"""simple docstring""" UpperCAmelCase_ : List[Any] = 9.8_0_6_6_5 def _A (__a , __a , __a = g ) -> float: """simple docstring""" if fluid_density <= 0: raise ValueError('''Impossible fluid density''' ) if volume < 0: raise ValueError('''Impossible Object volume''' ) if gravity <= 0: raise ValueError('''Impossible Gravity''' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
318
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
"""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. UpperCAmelCase_ : Union[str, Any] = abspath(join(dirname(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 _A (__a ) -> Union[str, Any]: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def _A (__a ) -> Any: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE_ : Optional[Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a , id=__a )
318
1
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers UpperCAmelCase_ : Union[str, Any] = float("""nan""") class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Union[str, Any] , lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = sys.stdout SCREAMING_SNAKE_CASE_ : str = open(lowercase_ , '''a''') def __getattr__( self : Union[str, Any] , lowercase_ : Dict): '''simple docstring''' return getattr(self.stdout , lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' self.stdout.write(lowercase_) # strip tqdm codes self.file.write(re.sub(r'''^.*\r''' , '''''' , lowercase_ , 0 , re.M)) def _A (__a=80 , __a=False ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [] # deal with critical env vars SCREAMING_SNAKE_CASE_ : List[str] = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: SCREAMING_SNAKE_CASE_ : int = os.environ.get(__a , __a ) if val is not None: cmd.append(f'{key}={val}' ) # python executable (not always needed if the script is executable) SCREAMING_SNAKE_CASE_ : Any = sys.executable if full_python_path else sys.executable.split('''/''' )[-1] cmd.append(__a ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : Tuple = '''''' while len(__a ) > 0: current_line += f'{cmd.pop(0 )} ' if len(__a ) == 0 or len(__a ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(__a ) SCREAMING_SNAKE_CASE_ : Dict = '''''' return "\\\n".join(__a ) def _A (__a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd ) # remove --output_dir if any and set our own SCREAMING_SNAKE_CASE_ : List[Any] = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd ) args.base_cmd += f' --output_dir {output_dir}' # ensure we have --overwrite_output_dir SCREAMING_SNAKE_CASE_ : List[str] = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def _A (__a , __a , __a , __a , __a , __a , __a ) -> str: """simple docstring""" if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 1_00 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22] )} , ) SCREAMING_SNAKE_CASE_ : List[Any] = subprocess.run(__a , capture_output=__a , text=__a ) if verbose: print('''STDOUT''' , result.stdout ) print('''STDERR''' , result.stderr ) # save the streams SCREAMING_SNAKE_CASE_ : Optional[Any] = variation.replace(''' ''' , '''-''' ) with open(Path(__a ) / f'log.{prefix}.stdout.txt' , '''w''' ) as f: f.write(result.stdout ) with open(Path(__a ) / f'log.{prefix}.stderr.txt' , '''w''' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('''failed''' ) return {target_metric_key: nan} with io.open(f'{output_dir}/all_results.json' , '''r''' , encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(__a ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def _A (__a , __a , __a , __a , __a , __a , __a , __a , __a , __a , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Optional[int] = [] SCREAMING_SNAKE_CASE_ : List[Any] = f'{id}: {variation:<{longest_variation_len}}' SCREAMING_SNAKE_CASE_ : Any = f'{preamble}: ' SCREAMING_SNAKE_CASE_ : str = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(__a ) , desc=__a , leave=__a ): SCREAMING_SNAKE_CASE_ : List[Any] = process_run_single( __a , __a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : List[Any] = single_run_metrics[target_metric_key] if not math.isnan(__a ): metrics.append(__a ) results.append(__a ) outcome += "✓" else: outcome += "✘" SCREAMING_SNAKE_CASE_ : List[str] = f'\33[2K\r{outcome}' if len(__a ) > 0: SCREAMING_SNAKE_CASE_ : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} SCREAMING_SNAKE_CASE_ : List[str] = round(mean_metrics[target_metric_key] , 2 ) SCREAMING_SNAKE_CASE_ : Tuple = f'{outcome} {mean_target}' if len(__a ) > 1: results_str += f' {tuple(round(__a , 2 ) for x in results )}' print(__a ) SCREAMING_SNAKE_CASE_ : Any = variation return mean_metrics else: print(__a ) return {variation_key: variation, target_metric_key: nan} def _A () -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = torch.cuda.get_device_properties(torch.device('''cuda''' ) ) return f'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def _A (__a , __a , __a , __a , __a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = pd.DataFrame(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''variation''' SCREAMING_SNAKE_CASE_ : List[Any] = '''diff_%''' SCREAMING_SNAKE_CASE_ : Optional[Any] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan SCREAMING_SNAKE_CASE_ : Optional[int] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(__a ): # as a fallback, use the minimal value as the sentinel SCREAMING_SNAKE_CASE_ : List[str] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(__a ): SCREAMING_SNAKE_CASE_ : Any = df.apply( lambda __a : round(1_00 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='''columns''' , ) # re-order columns SCREAMING_SNAKE_CASE_ : Dict = [variation_key, target_metric_key, diff_key, *report_metric_keys] SCREAMING_SNAKE_CASE_ : Union[str, Any] = df.reindex(__a , axis='''columns''' ) # reorder cols # capitalize SCREAMING_SNAKE_CASE_ : Union[str, Any] = df.rename(str.capitalize , axis='''columns''' ) # make the cols as narrow as possible SCREAMING_SNAKE_CASE_ : Optional[Any] = df.rename(lambda __a : c.replace('''_''' , '''<br>''' ) , axis='''columns''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = df.rename(lambda __a : c.replace('''_''' , '''\n''' ) , axis='''columns''' ) SCREAMING_SNAKE_CASE_ : int = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=__a , floatfmt='''.2f''' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=__a , floatfmt='''.2f''' )] print('''\n\n'''.join(__a ) ) def _A () -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '''--base-cmd''' , default=__a , type=__a , required=__a , help='''Base cmd''' , ) parser.add_argument( '''--variations''' , default=__a , type=__a , nargs='''+''' , required=__a , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , ) parser.add_argument( '''--base-variation''' , default=__a , type=__a , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , ) parser.add_argument( '''--target-metric-key''' , default=__a , type=__a , required=__a , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , ) parser.add_argument( '''--report-metric-keys''' , default='''''' , type=__a , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , ) parser.add_argument( '''--repeat-times''' , default=1 , type=__a , help='''How many times to re-run each variation - an average will be reported''' , ) parser.add_argument( '''--output_dir''' , default='''output_benchmark''' , type=__a , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , ) parser.add_argument( '''--verbose''' , default=__a , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , ) SCREAMING_SNAKE_CASE_ : Dict = parser.parse_args() SCREAMING_SNAKE_CASE_ : Tuple = args.output_dir Path(__a ).mkdir(exist_ok=__a ) SCREAMING_SNAKE_CASE_ : int = get_base_command(__a , __a ) # split each dimension into its --foo variations SCREAMING_SNAKE_CASE_ : Dict = [list(map(str.strip , re.split(R'''\|''' , __a ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty SCREAMING_SNAKE_CASE_ : List[str] = list(map(str.strip , map(''' '''.join , itertools.product(*__a ) ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = max(len(__a ) for x in variations ) # split wanted keys SCREAMING_SNAKE_CASE_ : Union[str, Any] = args.report_metric_keys.split() # capture prints into a log file for convenience SCREAMING_SNAKE_CASE_ : Union[str, Any] = f'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(f'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(f'and this script\'s output is also piped into {report_fn}' ) SCREAMING_SNAKE_CASE_ : int = Tee(__a ) print(f'\n*** Running {len(__a )} benchmarks:' ) print(f'Base command: {" ".join(__a )}' ) SCREAMING_SNAKE_CASE_ : Optional[int] = '''variation''' SCREAMING_SNAKE_CASE_ : str = [] for id, variation in enumerate(tqdm(__a , desc='''Total completion: ''' , leave=__a ) ): SCREAMING_SNAKE_CASE_ : str = base_cmd + variation.split() results.append( process_run( id + 1 , __a , __a , __a , __a , args.target_metric_key , __a , args.repeat_times , __a , args.verbose , ) ) process_results(__a , args.target_metric_key , __a , args.base_variation , __a ) if __name__ == "__main__": main()
318
"""simple docstring""" import argparse import os import re import packaging.version UpperCAmelCase_ : Any = """examples/""" UpperCAmelCase_ : Optional[int] = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCAmelCase_ : List[Any] = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCAmelCase_ : Optional[int] = """README.md""" def _A (__a , __a , __a ) -> int: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Optional[Any] = f.read() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = REPLACE_PATTERNS[pattern] SCREAMING_SNAKE_CASE_ : Optional[int] = replace.replace('''VERSION''' , __a ) SCREAMING_SNAKE_CASE_ : Tuple = re_pattern.sub(__a , __a ) with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(__a ) def _A (__a ) -> int: """simple docstring""" for folder, directories, fnames in os.walk(__a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__a , __a ) , __a , pattern='''examples''' ) def _A (__a , __a=False ) -> List[str]: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__a , __a , __a ) if not patch: update_version_in_examples(__a ) def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' SCREAMING_SNAKE_CASE_ : Optional[int] = '''1. Want to contribute a new model?''' with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Tuple = f.readlines() # Find the start of the list. SCREAMING_SNAKE_CASE_ : Tuple = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Dict = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): SCREAMING_SNAKE_CASE_ : List[Any] = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(__a , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__a ) def _A () -> List[str]: """simple docstring""" with open(REPLACE_FILES['''init'''] , '''r''' ) as f: SCREAMING_SNAKE_CASE_ : Any = f.read() SCREAMING_SNAKE_CASE_ : Dict = REPLACE_PATTERNS['''init'''][0].search(__a ).groups()[0] return packaging.version.parse(__a ) def _A (__a=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: SCREAMING_SNAKE_CASE_ : List[Any] = default_version.base_version elif patch: SCREAMING_SNAKE_CASE_ : int = f'{default_version.major}.{default_version.minor}.{default_version.micro + 1}' else: SCREAMING_SNAKE_CASE_ : Any = f'{default_version.major}.{default_version.minor + 1}.0' # Now let's ask nicely if that's the right one. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are you releasing? [{default_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = default_version print(f'Updating version to {version}.' ) global_version_update(__a , patch=__a ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def _A () -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_version() SCREAMING_SNAKE_CASE_ : Any = f'{current_version.major}.{current_version.minor + 1}.0.dev0' SCREAMING_SNAKE_CASE_ : Union[str, Any] = current_version.base_version # Check with the user we got that right. SCREAMING_SNAKE_CASE_ : int = input(f'Which version are we developing now? [{dev_version}]' ) if len(__a ) == 0: SCREAMING_SNAKE_CASE_ : Optional[int] = dev_version print(f'Updating version to {version}.' ) global_version_update(__a ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCAmelCase_ : int = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
318
1
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : List[str] = logging.getLogger(__name__) def _A () -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = argparse.ArgumentParser( description='''Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).''' ) parser.add_argument('''--file_path''' , type=__a , default='''data/dump.txt''' , help='''The path to the data.''' ) parser.add_argument('''--tokenizer_type''' , type=__a , default='''bert''' , choices=['''bert''', '''roberta''', '''gpt2'''] ) parser.add_argument('''--tokenizer_name''' , type=__a , default='''bert-base-uncased''' , help='''The tokenizer to use.''' ) parser.add_argument('''--dump_file''' , type=__a , default='''data/dump''' , help='''The dump file prefix.''' ) SCREAMING_SNAKE_CASE_ : Dict = parser.parse_args() logger.info(f'Loading Tokenizer ({args.tokenizer_name})' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE_ : int = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE_ : str = tokenizer.special_tokens_map['''cls_token'''] # `[CLS]` SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.special_tokens_map['''sep_token'''] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE_ : str = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE_ : str = tokenizer.special_tokens_map['''cls_token'''] # `<s>` SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.special_tokens_map['''sep_token'''] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE_ : Any = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE_ : str = tokenizer.special_tokens_map['''bos_token'''] # `<|endoftext|>` SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.special_tokens_map['''eos_token'''] # `<|endoftext|>` logger.info(f'Loading text from {args.file_path}' ) with open(args.file_path , '''r''' , encoding='''utf8''' ) as fp: SCREAMING_SNAKE_CASE_ : str = fp.readlines() logger.info('''Start encoding''' ) logger.info(f'{len(__a )} examples to process.' ) SCREAMING_SNAKE_CASE_ : Tuple = [] SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 1_00_00 SCREAMING_SNAKE_CASE_ : List[Any] = time.time() for text in data: SCREAMING_SNAKE_CASE_ : int = f'{bos} {text.strip()} {sep}' SCREAMING_SNAKE_CASE_ : Dict = tokenizer.encode(__a , add_special_tokens=__a ) rslt.append(__a ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = time.time() logger.info(f'{iter} examples processed. - {(end-start):.2f}s/{interval}expl' ) SCREAMING_SNAKE_CASE_ : Any = time.time() logger.info('''Finished binarization''' ) logger.info(f'{len(__a )} examples processed.' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = f'{args.dump_file}.{args.tokenizer_name}.pickle' SCREAMING_SNAKE_CASE_ : str = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE_ : Any = [np.uintaa(__a ) for d in rslt] else: SCREAMING_SNAKE_CASE_ : Optional[Any] = [np.intaa(__a ) for d in rslt] random.shuffle(rslt_ ) logger.info(f'Dump to {dp_file}' ) with open(__a , '''wb''' ) as handle: pickle.dump(rslt_ , __a , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
318
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _A (__a , __a , __a=1e-12 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T SCREAMING_SNAKE_CASE_ : List[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(__a , axis=1 ) , a_min=__a ) ).T return jnp.matmul(__a , norm_emb_a.T ) class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = jnp.floataa def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxCLIPVisionModule(self.config.vision_config) SCREAMING_SNAKE_CASE_ : Tuple = nn.Dense(self.config.projection_dim , use_bias=lowercase_ , dtype=self.dtype) SCREAMING_SNAKE_CASE_ : List[str] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim)) SCREAMING_SNAKE_CASE_ : Dict = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,)) def __call__( self : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.vision_model(lowercase_)[1] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.visual_projection(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.special_care_embeds) SCREAMING_SNAKE_CASE_ : List[str] = jax_cosine_distance(lowercase_ , self.concept_embeds) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs SCREAMING_SNAKE_CASE_ : Tuple = 0.0 SCREAMING_SNAKE_CASE_ : Dict = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment SCREAMING_SNAKE_CASE_ : Optional[int] = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : List[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=lowercase_) # Use a lower threshold if an image has any special care concept SCREAMING_SNAKE_CASE_ : Dict = is_special_care * 0.01 SCREAMING_SNAKE_CASE_ : str = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment SCREAMING_SNAKE_CASE_ : Any = jnp.round(lowercase_ , 3) SCREAMING_SNAKE_CASE_ : Dict = jnp.any(concept_scores > 0 , axis=1) return has_nsfw_concepts class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = CLIPConfig __UpperCamelCase = "clip_input" __UpperCamelCase = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Union[str, Any] , lowercase_ : CLIPConfig , lowercase_ : Optional[Tuple] = None , lowercase_ : int = 0 , lowercase_ : jnp.dtype = jnp.floataa , lowercase_ : bool = True , **lowercase_ : Any , ): '''simple docstring''' if input_shape is None: SCREAMING_SNAKE_CASE_ : List[str] = (1, 224, 224, 3) SCREAMING_SNAKE_CASE_ : List[Any] = self.module_class(config=lowercase_ , dtype=lowercase_ , **lowercase_) super().__init__(lowercase_ , lowercase_ , input_shape=lowercase_ , seed=lowercase_ , dtype=lowercase_ , _do_init=_do_init) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : jax.random.KeyArray , lowercase_ : Tuple , lowercase_ : FrozenDict = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = jax.random.normal(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = jax.random.split(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = {'''params''': params_rng, '''dropout''': dropout_rng} SCREAMING_SNAKE_CASE_ : List[Any] = self.module.init(lowercase_ , lowercase_)['''params'''] return random_params def __call__( self : List[Any] , lowercase_ : List[str] , lowercase_ : dict = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = jnp.transpose(lowercase_ , (0, 2, 3, 1)) return self.module.apply( {'''params''': params or self.params} , jnp.array(lowercase_ , dtype=jnp.floataa) , rngs={} , )
318
1
"""simple docstring""" UpperCAmelCase_ : Tuple = """Input must be a string of 8 numbers plus letter""" UpperCAmelCase_ : Dict = """TRWAGMYFPDXBNJZSQVHLCKE""" def _A (__a ) -> bool: """simple docstring""" if not isinstance(__a , __a ): SCREAMING_SNAKE_CASE_ : int = f'Expected string as input, found {type(__a ).__name__}' raise TypeError(__a ) SCREAMING_SNAKE_CASE_ : str = spanish_id.replace('''-''' , '''''' ).upper() if len(__a ) != 9: raise ValueError(__a ) try: SCREAMING_SNAKE_CASE_ : Optional[Any] = int(spanish_id_clean[0:8] ) SCREAMING_SNAKE_CASE_ : Dict = spanish_id_clean[8] except ValueError as ex: raise ValueError(__a ) from ex if letter.isdigit(): raise ValueError(__a ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
318
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = data SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None def _A () -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ : List[Any] = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() SCREAMING_SNAKE_CASE_ : Union[str, Any] = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = q.get() SCREAMING_SNAKE_CASE_ : List[str] = f'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : Optional[int] = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : List[str] = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ : str = f'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : str = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : Any = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : int = right_node q.put(__a ) raise def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Tuple = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : str = [] while not q.empty(): SCREAMING_SNAKE_CASE_ : List[str] = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ : Tuple = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ : str = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Any = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.left SCREAMING_SNAKE_CASE_ : Any = stack.pop() print(n.data , end=''',''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = [], [] SCREAMING_SNAKE_CASE_ : List[Any] = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ : List[str] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def _A (__a = "" , __a=50 , __a="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = divmod(width - len(__a ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase_ : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
318
1
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
318
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = "ssube/stable-diffusion-x4-upscaler-onnx" def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Union[str, Any]=0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor((1, 3, 128, 128) , rng=random.Random(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Dict = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase_) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Any = np.array( [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Tuple = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array( [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : List[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array( [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''') SCREAMING_SNAKE_CASE_ : int = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[int] = pipe(**lowercase_).images SCREAMING_SNAKE_CASE_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array( [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ort.SessionOptions() SCREAMING_SNAKE_CASE_ : Optional[int] = False return options def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : List[Any] = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=10 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Optional[int] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : int = np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''') SCREAMING_SNAKE_CASE_ : Tuple = init_image.resize((128, 128)) SCREAMING_SNAKE_CASE_ : Tuple = LMSDiscreteScheduler.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , subfolder='''scheduler''') SCREAMING_SNAKE_CASE_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , scheduler=lowercase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowercase_) SCREAMING_SNAKE_CASE_ : int = '''A fantasy landscape, trending on artstation''' SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0) SCREAMING_SNAKE_CASE_ : int = pipe( prompt=lowercase_ , image=lowercase_ , guidance_scale=7.5 , num_inference_steps=20 , generator=lowercase_ , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ : Optional[int] = output.images SCREAMING_SNAKE_CASE_ : Dict = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE_ : List[str] = np.array( [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2
318
1
"""simple docstring""" import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( '''kwargs, expected''' , [ ({'''num_shards''': 0, '''max_num_jobs''': 1}, []), ({'''num_shards''': 10, '''max_num_jobs''': 1}, [range(10 )]), ({'''num_shards''': 10, '''max_num_jobs''': 10}, [range(__a , i + 1 ) for i in range(10 )]), ({'''num_shards''': 1, '''max_num_jobs''': 10}, [range(1 )]), ({'''num_shards''': 10, '''max_num_jobs''': 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({'''num_shards''': 3, '''max_num_jobs''': 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def _A (__a , __a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = _distribute_shards(**__a ) assert out == expected @pytest.mark.parametrize( '''gen_kwargs, max_num_jobs, expected''' , [ ({'''foo''': 0}, 10, [{'''foo''': 0}]), ({'''shards''': [0, 1, 2, 3]}, 1, [{'''shards''': [0, 1, 2, 3]}]), ({'''shards''': [0, 1, 2, 3]}, 4, [{'''shards''': [0]}, {'''shards''': [1]}, {'''shards''': [2]}, {'''shards''': [3]}]), ({'''shards''': [0, 1]}, 4, [{'''shards''': [0]}, {'''shards''': [1]}]), ({'''shards''': [0, 1, 2, 3]}, 2, [{'''shards''': [0, 1]}, {'''shards''': [2, 3]}]), ] , ) def _A (__a , __a , __a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = _split_gen_kwargs(__a , __a ) assert out == expected @pytest.mark.parametrize( '''gen_kwargs, expected''' , [ ({'''foo''': 0}, 1), ({'''shards''': [0]}, 1), ({'''shards''': [0, 1, 2, 3]}, 4), ({'''shards''': [0, 1, 2, 3], '''foo''': 0}, 4), ({'''shards''': [0, 1, 2, 3], '''other''': (0, 1)}, 4), ({'''shards''': [0, 1, 2, 3], '''shards2''': [0, 1]}, RuntimeError), ] , ) def _A (__a , __a ) -> Union[str, Any]: """simple docstring""" if expected is RuntimeError: with pytest.raises(__a ): _number_of_shards_in_gen_kwargs(__a ) else: SCREAMING_SNAKE_CASE_ : Any = _number_of_shards_in_gen_kwargs(__a ) assert out == expected
318
"""simple docstring""" from scipy.stats import pearsonr import datasets UpperCAmelCase_ : List[Any] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ UpperCAmelCase_ : Optional[int] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ UpperCAmelCase_ : Tuple = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float'''), '''references''': datasets.Value('''float'''), }) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=False): '''simple docstring''' if return_pvalue: SCREAMING_SNAKE_CASE_ : int = pearsonr(lowercase_ , lowercase_) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(lowercase_ , lowercase_)[0])}
318
1