code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) _UpperCAmelCase : str = getLogger(__name__) def _SCREAMING_SNAKE_CASE ( __snake_case : Tuple , __snake_case : str , __snake_case : str , __snake_case : int = 8 , __snake_case : int = 1_0_2_4 , __snake_case : List[str]="val" , __snake_case : List[Any]=None , __snake_case : Dict=False , __snake_case : List[str]="summarization" , __snake_case : int=None , __snake_case : int=1 , __snake_case : Dict = None , __snake_case : str="" , **__snake_case : Tuple , ): _A = str(__snake_case ) assert local_rank is not None torch.distributed.init_process_group(backend='nccl' , rank=__snake_case ) _A = Path(__snake_case ) _A = save_dir.joinpath(F'rank_{local_rank}_output.json' ) torch.cuda.set_device(__snake_case ) _A = AutoModelForSeqaSeqLM.from_pretrained(__snake_case ).cuda() if fpaa: _A = model.half() # determine if we need to increase num_beams use_task_specific_params(__snake_case , __snake_case ) # update config with task specific params _A = generate_kwargs.pop('num_beams' , model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: _A = num_return_sequences _A = AutoTokenizer.from_pretrained(__snake_case ) logger.info(F'Inferred tokenizer type: {tokenizer.__class__}' ) # if this is wrong, check config.model_type. if max_source_length is None: _A = tokenizer.model_max_length if prefix is None: _A = prefix or getattr(model.config , 'prefix' , '' ) or '' _A = SeqaSeqDataset( __snake_case , __snake_case , __snake_case , max_target_length=1_0_2_4 , type_path=__snake_case , n_obs=__snake_case , prefix=__snake_case , **__snake_case , ) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. _A = ds.make_sortish_sampler(__snake_case , distributed=__snake_case , add_extra_examples=__snake_case , shuffle=__snake_case ) _A = DataLoader(__snake_case , sampler=__snake_case , batch_size=__snake_case , collate_fn=ds.collate_fn ) _A = [] for batch in tqdm(__snake_case ): _A = model.generate( input_ids=batch['input_ids'].to(model.device ) , attention_mask=batch['attention_mask'].to(model.device ) , num_return_sequences=__snake_case , num_beams=__snake_case , **__snake_case , ) _A = tokenizer.batch_decode(__snake_case , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _A = batch['ids'] if num_return_sequences > 1: _A = chunks(__snake_case , __snake_case ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(__snake_case ): results.append({'pred': pred, 'id': ids[i].item()} ) save_json(__snake_case , __snake_case ) return results, sampler.num_replicas def _SCREAMING_SNAKE_CASE ( ): _A = argparse.ArgumentParser( epilog='Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate' ) parser.add_argument('--data_dir' , type=__snake_case , help='like cnn_dm/test.source' ) parser.add_argument( '--model_name' , type=__snake_case , help='like facebook/bart-large-cnn,t5-base, etc.' , default='sshleifer/distilbart-xsum-12-3' , ) parser.add_argument('--save_dir' , type=__snake_case , help='where to save' , default='tmp_gen' ) parser.add_argument('--max_source_length' , type=__snake_case , default=__snake_case ) parser.add_argument( '--type_path' , type=__snake_case , default='test' , help='which subset to evaluate typically train/val/test' ) parser.add_argument('--task' , type=__snake_case , default='summarization' , help='used for task_specific_params + metrics' ) parser.add_argument('--bs' , type=__snake_case , default=8 , required=__snake_case , help='batch size' ) parser.add_argument( '--local_rank' , type=__snake_case , default=-1 , required=__snake_case , help='should be passed by distributed.launch' ) parser.add_argument( '--n_obs' , type=__snake_case , default=__snake_case , required=__snake_case , help='How many observations. Defaults to all.' ) parser.add_argument( '--num_return_sequences' , type=__snake_case , default=1 , required=__snake_case , help='How many sequences to return' ) parser.add_argument( '--sync_timeout' , type=__snake_case , default=6_0_0 , required=__snake_case , help='How long should master process wait for other processes to finish.' , ) parser.add_argument('--src_lang' , type=__snake_case , default=__snake_case , required=__snake_case ) parser.add_argument('--tgt_lang' , type=__snake_case , default=__snake_case , required=__snake_case ) parser.add_argument( '--prefix' , type=__snake_case , required=__snake_case , default=__snake_case , help='will be added to the begininng of src examples' ) parser.add_argument('--fp16' , action='store_true' ) parser.add_argument('--debug' , action='store_true' ) _A = time.time() _A , _A = parser.parse_known_args() _A = parse_numeric_n_bool_cl_kwargs(__snake_case ) if generate_kwargs and args.local_rank <= 0: print(F'parsed the following generate kwargs: {generate_kwargs}' ) _A = Path(args.save_dir + '_tmp' ) Path(__snake_case ).mkdir(exist_ok=__snake_case ) # this handles locking. _A = list(json_save_dir.glob('rank_*.json' ) ) if intermediate_files: raise ValueError(F'Found files at {json_save_dir} please move or remove them.' ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. _A = {} if args.src_lang is not None: _A = args.src_lang if args.tgt_lang is not None: _A = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=__snake_case ) _A , _A = eval_data_dir( args.data_dir , __snake_case , args.model_name , type_path=args.type_path , bs=args.bs , fpaa=args.fpaa , task=args.task , local_rank=args.local_rank , n_obs=args.n_obs , max_source_length=args.max_source_length , num_return_sequences=args.num_return_sequences , prefix=args.prefix , dataset_kwargs=__snake_case , **__snake_case , ) if args.local_rank <= 0: _A = Path(args.save_dir ) save_dir.mkdir(exist_ok=__snake_case ) _A = gather_results_from_each_node(__snake_case , __snake_case , args.sync_timeout ) _A = combine_partial_results(__snake_case ) if args.num_return_sequences > 1: _A = save_dir.joinpath('pseudolabel_results.json' ) print(F'Saving aggregated results at {save_path}, intermediate in {json_save_dir}/' ) save_json(__snake_case , __snake_case ) return _A = Path(args.data_dir ).joinpath(args.type_path + '.target' ) with open(__snake_case ) as f: _A = [x.rstrip() for x in f.readlines()][: len(__snake_case )] # Calculate metrics, save metrics, and save _generations.txt _A = 'translation' in args.task _A = calculate_bleu if calc_bleu else calculate_rouge _A = 'bleu' if calc_bleu else 'rouge' _A = score_fn(__snake_case , __snake_case ) _A = len(__snake_case ) _A = time.time() - start_time _A = round(runtime / metrics['n_obs'] , 4 ) _A = num_replicas # TODO(@stas00): add whatever metadata to metrics _A = save_dir.joinpath(F'{args.type_path}_{metric_name}.json' ) save_json(__snake_case , __snake_case , indent=__snake_case ) print(__snake_case ) write_txt_file(__snake_case , save_dir.joinpath(F'{args.type_path}_generations.txt' ) ) if args.debug: write_txt_file(__snake_case , save_dir.joinpath(F'{args.type_path}.target' ) ) else: shutil.rmtree(__snake_case ) def _SCREAMING_SNAKE_CASE ( __snake_case : int ): _A = [] for partial_result in partial_results: records.extend(__snake_case ) _A = sorted(__snake_case , key=lambda __snake_case : x["id"] ) _A = [x['pred'] for x in records] return preds def _SCREAMING_SNAKE_CASE ( __snake_case : List[str] , __snake_case : int , __snake_case : List[Any] ): # WAIT FOR lots of .json files _A = time.time() logger.info('waiting for all nodes to finish' ) _A = None while (time.time() - start_wait) < timeout: _A = list(save_dir.glob('rank_*.json' ) ) if len(__snake_case ) < num_replicas: continue try: # make sure all json files are fully saved _A = lmap(__snake_case , __snake_case ) return json_data except JSONDecodeError: continue else: raise TimeoutError('Rank 0 gave up on waiting for other processes' ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
107
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset _a = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class __A ( nn.Module ): '''simple docstring''' def __init__( self , __lowerCAmelCase ): '''simple docstring''' super().__init__() lowerCamelCase__ = torchvision.models.resnetaaa(pretrained=__lowerCAmelCase ) lowerCamelCase__ = list(model.children() )[:-2] lowerCamelCase__ = nn.Sequential(*__lowerCAmelCase ) lowerCamelCase__ = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = self.pool(self.model(__lowerCAmelCase ) ) lowerCamelCase__ = torch.flatten(__lowerCAmelCase , start_dim=2 ) lowerCamelCase__ = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class __A ( lowerCAmelCase ): '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = [json.loads(__lowerCAmelCase ) for l in open(__lowerCAmelCase )] lowerCamelCase__ = os.path.dirname(__lowerCAmelCase ) lowerCamelCase__ = tokenizer lowerCamelCase__ = labels lowerCamelCase__ = len(__lowerCAmelCase ) lowerCamelCase__ = max_seq_length lowerCamelCase__ = transforms def __len__( self ): '''simple docstring''' return len(self.data ) def __getitem__( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = torch.LongTensor(self.tokenizer.encode(self.data[index]['''text'''] , add_special_tokens=__lowerCAmelCase ) ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = sentence[0], sentence[1:-1], sentence[-1] lowerCamelCase__ = sentence[: self.max_seq_length] lowerCamelCase__ = torch.zeros(self.n_classes ) lowerCamelCase__ = 1 lowerCamelCase__ = Image.open(os.path.join(self.data_dir , self.data[index]['''img'''] ) ).convert('''RGB''' ) lowerCamelCase__ = self.transforms(__lowerCAmelCase ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = Counter() for row in self.data: label_freqs.update(row['''label'''] ) return label_freqs def lowerCAmelCase__(__snake_case ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase__ = [len(row['''sentence'''] ) for row in batch] lowerCamelCase__ , lowerCamelCase__ = len(__snake_case ), max(__snake_case ) lowerCamelCase__ = torch.zeros(__snake_case ,__snake_case ,dtype=torch.long ) lowerCamelCase__ = torch.zeros(__snake_case ,__snake_case ,dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(__snake_case ,__snake_case ) ): lowerCamelCase__ = input_row['''sentence'''] lowerCamelCase__ = 1 lowerCamelCase__ = torch.stack([row['''image'''] for row in batch] ) lowerCamelCase__ = torch.stack([row['''label'''] for row in batch] ) lowerCamelCase__ = torch.stack([row['''image_start_token'''] for row in batch] ) lowerCamelCase__ = torch.stack([row['''image_end_token'''] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def lowerCAmelCase__() -> Optional[int]: '''simple docstring''' return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def lowerCAmelCase__() -> Any: '''simple docstring''' return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.4_6_7_7_7_0_4_4, 0.4_4_5_3_1_4_2_9, 0.4_0_6_6_1_0_1_7] ,std=[0.1_2_2_2_1_9_9_4, 0.1_2_1_4_5_8_3_5, 0.1_4_3_8_0_4_6_9] ,), ] )
481
0
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 lowerCamelCase_ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = [2, 2, 6, 2] if 'tiny' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE = True if 'large' in model_name or 'huge' in model_name else False SCREAMING_SNAKE_CASE = True if 'large' in model_name or 'huge' in model_name else False SCREAMING_SNAKE_CASE = 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: SCREAMING_SNAKE_CASE = [3, 3, 3, 3] SCREAMING_SNAKE_CASE = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE = [4, 4, 4, 4] SCREAMING_SNAKE_CASE = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE = 1_28 elif "large" in model_name: SCREAMING_SNAKE_CASE = 1_92 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE = 2_56 elif "huge" in model_name: SCREAMING_SNAKE_CASE = 3_52 # set label information SCREAMING_SNAKE_CASE = 'huggingface/label-files' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE = 'imagenet-22k-id2label.json' else: SCREAMING_SNAKE_CASE = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = FocalNetConfig( embed_dim=lowerCAmelCase__ , depths=lowerCAmelCase__ , focal_levels=lowerCAmelCase__ , focal_windows=lowerCAmelCase__ , use_conv_embed=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , use_post_layernorm=lowerCAmelCase__ , use_layerscale=lowerCAmelCase__ , ) return config def lowerCamelCase_ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = 'encoder.' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE = name.replace("""encoder.layers""" , """encoder.stages""" ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""downsample.proj""" , """downsample.projection""" ) if "blocks" in name: SCREAMING_SNAKE_CASE = name.replace("""blocks""" , """layers""" ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE = name.replace("""modulation.f""" , """modulation.projection_in""" ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE = name.replace("""modulation.h""" , """modulation.projection_context""" ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE = name.replace("""modulation.proj""" , """modulation.projection_out""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = 'layernorm.weight' if name == "norm.bias": SCREAMING_SNAKE_CASE = 'layernorm.bias' if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = 'focalnet.' + name return name def lowerCamelCase_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ): '''simple docstring''' SCREAMING_SNAKE_CASE = { '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 SCREAMING_SNAKE_CASE = model_name_to_url[model_name] print("""Checkpoint URL: """ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location="""cpu""" )['model'] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE = state_dict.pop(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = get_focalnet_config(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = FocalNetForImageClassification(lowerCAmelCase__ ) model.eval() # load state dict model.load_state_dict(lowerCAmelCase__ ) # verify conversion SCREAMING_SNAKE_CASE = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE = BitImageProcessor( do_resize=lowerCAmelCase__ , size={"""shortest_edge""": 2_56} , resample=PILImageResampling.BILINEAR , do_center_crop=lowerCAmelCase__ , crop_size=2_24 , do_normalize=lowerCAmelCase__ , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) SCREAMING_SNAKE_CASE = processor(images=lowerCAmelCase__ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = transforms.Compose( [ transforms.Resize(2_56 ), transforms.CenterCrop(2_24 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) SCREAMING_SNAKE_CASE = image_transforms(lowerCAmelCase__ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , lowerCAmelCase__ , atol=1E-4 ) SCREAMING_SNAKE_CASE = model(**lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = 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": SCREAMING_SNAKE_CASE = torch.tensor([0.2_166, -0.4_368, 0.2_191] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE = torch.tensor([1.1_669, 0.0_125, -0.1_695] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE = torch.tensor([0.4_917, -0.0_430, 0.1_341] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE = torch.tensor([-0.2_588, -0.5_342, -0.2_331] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE = torch.tensor([-0.1_655, -0.4_090, -0.1_730] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE = torch.tensor([0.5_306, -0.0_483, -0.3_928] ) assert torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , 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(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) 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__": __A : 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.""", ) __A : List[str] = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
709
import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __A : Any = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right __A : Optional[int] = 2_5_6_0_4_7 __A : Dict = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( A , unittest.TestCase ): '''simple docstring''' a__ = NllbTokenizer a__ = NllbTokenizerFast a__ = True a__ = True a__ = {} def _UpperCAmelCase ( self : Any ) -> int: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = NllbTokenizer(a , keep_accents=a ) tokenizer.save_pretrained(self.tmpdirname ) def _UpperCAmelCase ( self : int ) -> str: SCREAMING_SNAKE_CASE = NllbTokenizer(a , keep_accents=a ) SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(a , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( a , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(a ) self.assertListEqual( a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(a ) self.assertListEqual( a , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def _UpperCAmelCase ( self : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(a ) SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(a ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(a , a ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(a ) SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a ) ) shutil.rmtree(a ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(a , legacy_format=a ) SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(a ) # Checks it save with the same files self.assertSequenceEqual(a , a ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(a ) SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a ) ) shutil.rmtree(a ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(a , legacy_format=a ) SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(a ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(a ) SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a ) ) shutil.rmtree(a ) @require_torch def _UpperCAmelCase ( self : Dict ) -> List[str]: if not self.test_seqaseq: return SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Longer text that will definitely require truncation. SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=a , tgt_texts=a , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( a , tgt_texts=a , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=a , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , a ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def _UpperCAmelCase ( self : int ) -> Optional[int]: pass def _UpperCAmelCase ( self : Optional[int] ) -> Optional[int]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=a )] SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( a , additional_special_tokens=a , **a ) SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=a )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( a , additional_special_tokens=a , **a , ) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( a , additional_special_tokens=a , **a ) SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(a , a ) self.assertEqual(a , a ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' a__ = '''facebook/nllb-200-distilled-600M''' a__ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] a__ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] a__ = [ 2_5_6_0_4_7, 1_6_2_9_7, 1_3_4_4_0_8, 8_1_6_5, 2_4_8_0_6_6, 1_4_7_3_4, 9_5_0, 1_1_3_5, 1_0_5_7_2_1, 3_5_7_3, 8_3, 2_7_3_5_2, 1_0_8, 4_9_4_8_6, 2, ] @classmethod def _UpperCAmelCase ( cls : List[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) SCREAMING_SNAKE_CASE = 1 return cls def _UpperCAmelCase ( self : Dict ) -> Dict: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def _UpperCAmelCase ( self : Optional[int] ) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , a ) def _UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: self.assertIn(a , self.tokenizer.all_special_ids ) # fmt: off SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on SCREAMING_SNAKE_CASE = self.tokenizer.decode(a , skip_special_tokens=a ) SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=a ) self.assertEqual(a , a ) self.assertNotIn(self.tokenizer.eos_token , a ) def _UpperCAmelCase ( self : Optional[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , a ) SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = self.tokenizer(a , max_length=a , truncation=a ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , a ) self.assertEqual(len(a ) , a ) def _UpperCAmelCase ( self : Dict ) -> Any: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def _UpperCAmelCase ( self : str ) -> Optional[int]: SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(a ) SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(a ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , a ) @require_torch def _UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=a , truncation=a , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(a , a ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , a ) self.assertEqual(a , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def _UpperCAmelCase ( self : str ) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=a , truncation=a , max_length=3 , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=a , truncation=a , max_length=10 , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = targets["""input_ids"""] SCREAMING_SNAKE_CASE = shift_tokens_right( a , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _UpperCAmelCase ( self : int ) -> Optional[int]: SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(a ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def _UpperCAmelCase ( self : str ) -> int: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
450
0
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") class _lowerCAmelCase ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a_ : Any =BartphoTokenizer a_ : Optional[int] =False a_ : List[Any] =True def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' super().setUp() _snake_case : List[str] = ['▁This', '▁is', '▁a', '▁t', 'est'] _snake_case : Tuple = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) _snake_case : Any = {'unk_token': '<unk>'} _snake_case : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['monolingual_vocab_file'] ) with open(self.monolingual_vocab_file , 'w' , encoding='utf-8' ) as fp: for token in vocab_tokens: fp.write(f"""{token} {vocab_tokens[token]}\n""" ) _snake_case : List[str] = BartphoTokenizer(UpperCamelCase , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : List[str] , **UpperCamelCase : List[str] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase_ ( self : str , UpperCamelCase : int ): '''simple docstring''' _snake_case : Dict = 'This is a là test' _snake_case : Union[str, Any] = 'This is a<unk><unk> test' return input_text, output_text def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' _snake_case : Optional[Any] = BartphoTokenizer(UpperCamelCase , self.monolingual_vocab_file , **self.special_tokens_map ) _snake_case : Tuple = 'This is a là test' _snake_case : Any = '▁This ▁is ▁a ▁l à ▁t est'.split() _snake_case : List[Any] = tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) _snake_case : Dict = tokens + [tokenizer.unk_token] _snake_case : int = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , UpperCamelCase )
411
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class _lowerCAmelCase ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[Any] ): '''simple docstring''' _snake_case : Any = [] def UpperCamelCase_ ( self : int , UpperCamelCase : Union[str, Any] , UpperCamelCase : Tuple , UpperCamelCase : int , **UpperCamelCase : Any ): '''simple docstring''' self.events.append('on_init_end' ) def UpperCamelCase_ ( self : Optional[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] , **UpperCamelCase : List[Any] ): '''simple docstring''' self.events.append('on_train_begin' ) def UpperCamelCase_ ( self : Tuple , UpperCamelCase : Optional[Any] , UpperCamelCase : Dict , UpperCamelCase : List[str] , **UpperCamelCase : Any ): '''simple docstring''' self.events.append('on_train_end' ) def UpperCamelCase_ ( self : List[Any] , UpperCamelCase : List[Any] , UpperCamelCase : Any , UpperCamelCase : str , **UpperCamelCase : str ): '''simple docstring''' self.events.append('on_epoch_begin' ) def UpperCamelCase_ ( self : Optional[int] , UpperCamelCase : int , UpperCamelCase : List[Any] , UpperCamelCase : str , **UpperCamelCase : Optional[Any] ): '''simple docstring''' self.events.append('on_epoch_end' ) def UpperCamelCase_ ( self : Any , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , **UpperCamelCase : Optional[Any] ): '''simple docstring''' self.events.append('on_step_begin' ) def UpperCamelCase_ ( self : Tuple , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , **UpperCamelCase : Dict ): '''simple docstring''' self.events.append('on_step_end' ) def UpperCamelCase_ ( self : str , UpperCamelCase : Any , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , **UpperCamelCase : Union[str, Any] ): '''simple docstring''' self.events.append('on_evaluate' ) def UpperCamelCase_ ( self : List[Any] , UpperCamelCase : List[str] , UpperCamelCase : Optional[int] , UpperCamelCase : str , **UpperCamelCase : List[Any] ): '''simple docstring''' self.events.append('on_predict' ) def UpperCamelCase_ ( self : int , UpperCamelCase : int , UpperCamelCase : Tuple , UpperCamelCase : int , **UpperCamelCase : Optional[int] ): '''simple docstring''' self.events.append('on_save' ) def UpperCamelCase_ ( self : Optional[int] , UpperCamelCase : Optional[Any] , UpperCamelCase : List[str] , UpperCamelCase : Any , **UpperCamelCase : Union[str, Any] ): '''simple docstring''' self.events.append('on_log' ) def UpperCamelCase_ ( self : Union[str, Any] , UpperCamelCase : str , UpperCamelCase : Any , UpperCamelCase : str , **UpperCamelCase : Dict ): '''simple docstring''' self.events.append('on_prediction_step' ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _snake_case : str = tempfile.mkdtemp() def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' shutil.rmtree(self.output_dir ) def UpperCamelCase_ ( self : Union[str, Any] , UpperCamelCase : Tuple=0 , UpperCamelCase : str=0 , UpperCamelCase : str=64 , UpperCamelCase : str=64 , UpperCamelCase : List[Any]=None , UpperCamelCase : Union[str, Any]=False , **UpperCamelCase : List[str] ): '''simple docstring''' _snake_case : Tuple = RegressionDataset(length=UpperCamelCase ) _snake_case : int = RegressionDataset(length=UpperCamelCase ) _snake_case : Tuple = RegressionModelConfig(a=UpperCamelCase , b=UpperCamelCase ) _snake_case : Union[str, Any] = RegressionPreTrainedModel(UpperCamelCase ) _snake_case : Optional[Any] = TrainingArguments(self.output_dir , disable_tqdm=UpperCamelCase , report_to=[] , **UpperCamelCase ) return Trainer( UpperCamelCase , UpperCamelCase , train_dataset=UpperCamelCase , eval_dataset=UpperCamelCase , callbacks=UpperCamelCase , ) def UpperCamelCase_ ( self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) # Order doesn't matter _snake_case : Optional[Any] = sorted(UpperCamelCase , key=lambda UpperCamelCase : cb.__name__ if isinstance(UpperCamelCase , UpperCamelCase ) else cb.__class__.__name__ ) _snake_case : Dict = sorted(UpperCamelCase , key=lambda UpperCamelCase : cb.__name__ if isinstance(UpperCamelCase , UpperCamelCase ) else cb.__class__.__name__ ) for cba, cba in zip(UpperCamelCase , UpperCamelCase ): if isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ): self.assertEqual(UpperCamelCase , UpperCamelCase ) elif isinstance(UpperCamelCase , UpperCamelCase ) and not isinstance(UpperCamelCase , UpperCamelCase ): self.assertEqual(UpperCamelCase , cba.__class__ ) elif not isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ): self.assertEqual(cba.__class__ , UpperCamelCase ) else: self.assertEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase_ ( self : Dict , UpperCamelCase : Dict ): '''simple docstring''' _snake_case : Dict = ['on_init_end', 'on_train_begin'] _snake_case : List[str] = 0 _snake_case : str = len(trainer.get_eval_dataloader() ) _snake_case : str = ['on_prediction_step'] * len(trainer.get_eval_dataloader() ) + ['on_log', 'on_evaluate'] for _ in range(trainer.state.num_train_epochs ): expected_events.append('on_epoch_begin' ) for _ in range(UpperCamelCase ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('on_log' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('on_save' ) expected_events.append('on_epoch_end' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def UpperCamelCase_ ( self : str ): '''simple docstring''' _snake_case : int = self.get_trainer() _snake_case : List[Any] = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) # Callbacks passed at init are added to the default callbacks _snake_case : Union[str, Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback _snake_case : Tuple = self.get_trainer(disable_tqdm=UpperCamelCase ) _snake_case : Optional[int] = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' _snake_case : Tuple = DEFAULT_CALLBACKS.copy() + [ProgressCallback] _snake_case : List[Any] = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(UpperCamelCase ) expected_callbacks.remove(UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) _snake_case : Optional[Any] = self.get_trainer() _snake_case : Dict = trainer.pop_callback(UpperCamelCase ) self.assertEqual(cb.__class__ , UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) trainer.add_callback(UpperCamelCase ) expected_callbacks.insert(0 , UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) # We can also add, pop, or remove by instance _snake_case : Optional[Any] = self.get_trainer() _snake_case : Optional[int] = trainer.callback_handler.callbacks[0] trainer.remove_callback(UpperCamelCase ) expected_callbacks.remove(UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) _snake_case : int = self.get_trainer() _snake_case : int = trainer.callback_handler.callbacks[0] _snake_case : int = trainer.pop_callback(UpperCamelCase ) self.assertEqual(UpperCamelCase , UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) trainer.add_callback(UpperCamelCase ) expected_callbacks.insert(0 , UpperCamelCase ) self.check_callbacks_equality(trainer.callback_handler.callbacks , UpperCamelCase ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='ignore' , category=UpperCamelCase ) _snake_case : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() _snake_case : List[str] = trainer.callback_handler.callbacks[-2].events self.assertEqual(UpperCamelCase , self.get_expected_events(UpperCamelCase ) ) # Independent log/save/eval _snake_case : Optional[Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() _snake_case : List[Any] = trainer.callback_handler.callbacks[-2].events self.assertEqual(UpperCamelCase , self.get_expected_events(UpperCamelCase ) ) _snake_case : Optional[int] = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() _snake_case : Dict = trainer.callback_handler.callbacks[-2].events self.assertEqual(UpperCamelCase , self.get_expected_events(UpperCamelCase ) ) _snake_case : List[Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='steps' ) trainer.train() _snake_case : Union[str, Any] = trainer.callback_handler.callbacks[-2].events self.assertEqual(UpperCamelCase , self.get_expected_events(UpperCamelCase ) ) _snake_case : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='epoch' ) trainer.train() _snake_case : str = trainer.callback_handler.callbacks[-2].events self.assertEqual(UpperCamelCase , self.get_expected_events(UpperCamelCase ) ) # A bit of everything _snake_case : int = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='steps' , ) trainer.train() _snake_case : Tuple = trainer.callback_handler.callbacks[-2].events self.assertEqual(UpperCamelCase , self.get_expected_events(UpperCamelCase ) ) # warning should be emitted for duplicated callbacks with patch('transformers.trainer_callback.logger.warning' ) as warn_mock: _snake_case : Dict = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(UpperCamelCase ) in warn_mock.call_args[0][0]
411
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase_ ( UpperCamelCase ): '''simple docstring''' def __init__( self , __A , __A ): """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase : Optional[int] = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , __A = 1 , __A = None , __A = 0.0 , __A = 50 , __A = None , __A = "pil" , __A = True , ): """simple docstring""" if isinstance(self.unet.config.sample_size , _SCREAMING_SNAKE_CASE ): lowerCamelCase : Dict = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: lowerCamelCase : str = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) lowerCamelCase : Optional[Any] = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowerCamelCase : int = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase : Union[str, Any] = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE ).prev_sample lowerCamelCase : Dict = (image / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase : List[Any] = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
713
def lowercase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' if bit_count < 0: raise ValueError("The given input must be positive" ) # get the generated string sequence lowerCamelCase : str = gray_code_sequence_string(SCREAMING_SNAKE_CASE_ ) # # convert them to integers for i in range(len(SCREAMING_SNAKE_CASE_ ) ): lowerCamelCase : Union[str, Any] = int(sequence[i] , 2 ) return sequence def lowercase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] lowerCamelCase : int = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits lowerCamelCase : Any = gray_code_sequence_string(bit_count - 1 ) lowerCamelCase : Optional[int] = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): lowerCamelCase : Union[str, Any] = "0" + smaller_sequence[i] sequence.append(SCREAMING_SNAKE_CASE_ ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): lowerCamelCase : str = "1" + smaller_sequence[i] sequence.append(SCREAMING_SNAKE_CASE_ ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
231
0
from math import ceil def __lowerCamelCase ( UpperCamelCase__ = 1001 ): '''simple docstring''' snake_case_ = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): snake_case_ = 2 * i + 1 snake_case_ = 2 * i snake_case_ = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: _UpperCAmelCase : Optional[Any] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number""")
362
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class lowercase ( unittest.TestCase ): def a ( self ): snake_case_ = 10 def a ( self ): snake_case_ = [1, 2, 3, 4] snake_case_ = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(snake_case , self.block_size , 0 ) , snake_case ) def a ( self ): snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(snake_case , self.block_size , 0 ) , snake_case ) def a ( self ): snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] snake_case_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(snake_case , self.block_size , 0 ) , snake_case ) def a ( self ): snake_case_ = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' snake_case_ , snake_case_ = process_story(snake_case ) self.assertEqual(snake_case , [] ) def a ( self ): snake_case_ = '' snake_case_ , snake_case_ = process_story(snake_case ) self.assertEqual(snake_case , [] ) self.assertEqual(snake_case , [] ) def a ( self ): snake_case_ = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) snake_case_ , snake_case_ = process_story(snake_case ) snake_case_ = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(snake_case , snake_case ) snake_case_ = ['It was the best of times.'] self.assertEqual(snake_case , snake_case ) def a ( self ): snake_case_ = torch.tensor([1, 2, 3, 4] ) snake_case_ = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(snake_case , 0 ).numpy() , expected.numpy() ) def a ( self ): snake_case_ = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) snake_case_ = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(snake_case , 23 ).numpy() , expected.numpy() ) def a ( self ): snake_case_ = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) snake_case_ = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(snake_case , 1 ).numpy() , expected.numpy() ) def a ( self ): snake_case_ = 101 snake_case_ = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) snake_case_ = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) snake_case_ = compute_token_type_ids(snake_case , snake_case ) np.testing.assert_array_equal(snake_case , snake_case )
362
1
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class a_ ( lowerCamelCase ): lowercase = (CMStochasticIterativeScheduler,) lowercase = 10 def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase = { """num_train_timesteps""": 201, """sigma_min""": 0.0_0_2, """sigma_max""": 8_0.0, } config.update(**_SCREAMING_SNAKE_CASE ) return config def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = 10 UpperCamelCase = self.get_scheduler_config() UpperCamelCase = self.scheduler_classes[0](**_SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ) UpperCamelCase = scheduler.timesteps[0] UpperCamelCase = scheduler.timesteps[1] UpperCamelCase = self.dummy_sample UpperCamelCase = 0.1 * sample UpperCamelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).prev_sample UpperCamelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def A__ ( self ) -> Tuple: """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = 1 scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ) UpperCamelCase = scheduler.timesteps UpperCamelCase = torch.manual_seed(0 ) UpperCamelCase = self.dummy_model() UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(_SCREAMING_SNAKE_CASE ): # 1. scale model input UpperCamelCase = scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 2. predict noise residual UpperCamelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 3. predict previous sample x_t-1 UpperCamelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE ).prev_sample UpperCamelCase = pred_prev_sample UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = [106, 0] scheduler.set_timesteps(timesteps=_SCREAMING_SNAKE_CASE ) UpperCamelCase = scheduler.timesteps UpperCamelCase = torch.manual_seed(0 ) UpperCamelCase = self.dummy_model() UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input UpperCamelCase = scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 2. predict noise residual UpperCamelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # 3. predict previous sample x_t-1 UpperCamelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE ).prev_sample UpperCamelCase = pred_prev_sample UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = [39, 30, 12, 15, 0] with self.assertRaises(_SCREAMING_SNAKE_CASE , msg="""`timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = [39, 30, 12, 1, 0] UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) with self.assertRaises(_SCREAMING_SNAKE_CASE , msg="""Can only pass one of `num_inference_steps` or `timesteps`.""" ): scheduler.set_timesteps(num_inference_steps=_SCREAMING_SNAKE_CASE , timesteps=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = [scheduler.config.num_train_timesteps] with self.assertRaises( _SCREAMING_SNAKE_CASE , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=_SCREAMING_SNAKE_CASE )
35
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase ,UpperCamelCase = emb.weight.shape UpperCamelCase = nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase ) UpperCamelCase = emb.weight.data return lin_layer def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" ) UpperCamelCase = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] UpperCamelCase = mam_aaa["""model"""] remove_ignore_keys_(__UpperCamelCase ) UpperCamelCase = state_dict["""encoder.embed_tokens.weight"""].shape[0] UpperCamelCase = MaMaaaConfig( vocab_size=__UpperCamelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) UpperCamelCase = state_dict["""decoder.embed_tokens.weight"""] UpperCamelCase = MaMaaaForConditionalGeneration(__UpperCamelCase ) model.model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) UpperCamelCase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
35
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def a__ ( lowerCAmelCase__ , lowerCAmelCase__=False ) -> Dict: UpperCAmelCase__ : int = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('''module.cls_token''', '''vit.embeddings.cls_token'''), ('''module.patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''module.patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''module.pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''module.norm.weight''', '''layernorm.weight'''), ('''module.norm.bias''', '''layernorm.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" UpperCAmelCase__ : Dict = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ) -> str: for i in range(config.num_hidden_layers ): if base_model: UpperCAmelCase__ : str = '''''' else: UpperCAmelCase__ : Union[str, Any] = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase__ : Optional[int] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" ) UpperCAmelCase__ : Optional[int] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase__ : Optional[int] = in_proj_bias[: config.hidden_size] UpperCAmelCase__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase__ : Dict = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase__ : Optional[int] = in_proj_bias[-config.hidden_size :] def a__ ( lowerCAmelCase__ ) -> Union[str, Any]: UpperCAmelCase__ : Optional[Any] = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(lowerCAmelCase__ , lowerCAmelCase__ ) def a__ ( lowerCAmelCase__ ) -> Any: # projection head is used in the self-supervised pre-training in MSN, # for downstream task it's not needed. UpperCAmelCase__ : List[str] = [ '''module.fc.fc1.weight''', '''module.fc.fc1.bias''', '''module.fc.bn1.weight''', '''module.fc.bn1.bias''', '''module.fc.bn1.running_mean''', '''module.fc.bn1.running_var''', '''module.fc.bn1.num_batches_tracked''', '''module.fc.fc2.weight''', '''module.fc.fc2.bias''', '''module.fc.bn2.weight''', '''module.fc.bn2.bias''', '''module.fc.bn2.running_mean''', '''module.fc.bn2.running_var''', '''module.fc.bn2.num_batches_tracked''', '''module.fc.fc3.weight''', '''module.fc.fc3.bias''', ] for k in ignore_keys: state_dict.pop(lowerCAmelCase__ , lowerCAmelCase__ ) def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: UpperCAmelCase__ : List[Any] = dct.pop(lowerCAmelCase__ ) UpperCAmelCase__ : Optional[int] = val def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: UpperCAmelCase__ : str = ViTMSNConfig() UpperCAmelCase__ : Optional[int] = 10_00 UpperCAmelCase__ : List[Any] = '''datasets/huggingface/label-files''' UpperCAmelCase__ : str = '''imagenet-1k-id2label.json''' UpperCAmelCase__ : List[str] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ ) , '''r''' ) ) UpperCAmelCase__ : Union[str, Any] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} UpperCAmelCase__ : List[str] = idalabel UpperCAmelCase__ : Optional[int] = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: UpperCAmelCase__ : List[str] = 3_84 UpperCAmelCase__ : Dict = 15_36 UpperCAmelCase__ : Tuple = 6 elif "l16" in checkpoint_url: UpperCAmelCase__ : List[str] = 10_24 UpperCAmelCase__ : str = 40_96 UpperCAmelCase__ : Tuple = 24 UpperCAmelCase__ : Optional[int] = 16 UpperCAmelCase__ : Optional[int] = 0.1 elif "b4" in checkpoint_url: UpperCAmelCase__ : List[str] = 4 elif "l7" in checkpoint_url: UpperCAmelCase__ : int = 7 UpperCAmelCase__ : int = 10_24 UpperCAmelCase__ : Dict = 40_96 UpperCAmelCase__ : Any = 24 UpperCAmelCase__ : str = 16 UpperCAmelCase__ : Any = 0.1 UpperCAmelCase__ : str = ViTMSNModel(lowerCAmelCase__ ) UpperCAmelCase__ : Optional[Any] = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' )['''target_encoder'''] UpperCAmelCase__ : Union[str, Any] = ViTImageProcessor(size=config.image_size ) remove_projection_head(lowerCAmelCase__ ) UpperCAmelCase__ : List[Any] = create_rename_keys(lowerCAmelCase__ , base_model=lowerCAmelCase__ ) for src, dest in rename_keys: rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) read_in_q_k_v(lowerCAmelCase__ , lowerCAmelCase__ , base_model=lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) model.eval() UpperCAmelCase__ : Dict = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase__ : Tuple = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) UpperCAmelCase__ : Tuple = ViTImageProcessor( size=config.image_size , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ ) UpperCAmelCase__ : Optional[Any] = image_processor(images=lowerCAmelCase__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) UpperCAmelCase__ : Optional[Any] = model(**lowerCAmelCase__ ) UpperCAmelCase__ : Tuple = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: UpperCAmelCase__ : Any = torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]] ) elif "b16" in checkpoint_url: UpperCAmelCase__ : Optional[int] = torch.tensor([[1_4.2_8_8_9, -1_8.9_0_4_5, 1_1.7_2_8_1]] ) elif "l16" in checkpoint_url: UpperCAmelCase__ : int = torch.tensor([[4_1.5_0_2_8, -2_2.8_6_8_1, 4_5.6_4_7_5]] ) elif "b4" in checkpoint_url: UpperCAmelCase__ : str = torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]] ) else: UpperCAmelCase__ : Tuple = torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', 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__ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
75
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=7 , lowerCAmelCase_=False , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_=True , lowerCAmelCase_=33 , lowerCAmelCase_=32 , lowerCAmelCase_=5 , lowerCAmelCase_=4 , lowerCAmelCase_=37 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=5_12 , lowerCAmelCase_=16 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=3 , lowerCAmelCase_=4 , lowerCAmelCase_=None , ): """simple docstring""" _snake_case = parent _snake_case = batch_size _snake_case = seq_length _snake_case = is_training _snake_case = use_input_mask _snake_case = use_token_type_ids _snake_case = use_labels _snake_case = vocab_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = type_sequence_label_size _snake_case = initializer_range _snake_case = num_labels _snake_case = num_choices _snake_case = scope def lowerCamelCase ( self ): """simple docstring""" _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = None if self.use_input_mask: _snake_case = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case = None _snake_case = None _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _snake_case = ids_tensor([self.batch_size] , self.num_choices ) _snake_case = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase ( self ): """simple docstring""" return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , 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 , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = EsmModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) _snake_case = model(lowerCAmelCase_ ) _snake_case = model(lowerCAmelCase_ ) 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 lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = EsmForMaskedLM(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_labels _snake_case = EsmForTokenClassification(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) = config_and_inputs _snake_case = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): __lowercase = False __lowercase = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __lowercase = () __lowercase = ( { """feature-extraction""": EsmModel, """fill-mask""": EsmForMaskedLM, """text-classification""": EsmForSequenceClassification, """token-classification""": EsmForTokenClassification, """zero-shot""": EsmForSequenceClassification, } if is_torch_available() else {} ) __lowercase = True def lowerCamelCase ( self ): """simple docstring""" _snake_case = EsmModelTester(self ) _snake_case = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=37 ) def lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _snake_case = type self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase_ ) @slow def lowerCamelCase ( self ): """simple docstring""" for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = EsmModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs()[0] _snake_case = EsmEmbeddings(config=lowerCAmelCase_ ) _snake_case = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) _snake_case = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _snake_case = create_position_ids_from_input_ids(lowerCAmelCase_ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs()[0] _snake_case = EsmEmbeddings(config=lowerCAmelCase_ ) _snake_case = torch.empty(2 , 4 , 30 ) _snake_case = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _snake_case = torch.as_tensor([expected_single_positions, expected_single_positions] ) _snake_case = embeddings.create_position_ids_from_inputs_embeds(lowerCAmelCase_ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) @unittest.skip('Esm does not support embedding resizing' ) def lowerCamelCase ( self ): """simple docstring""" pass @unittest.skip('Esm does not support embedding resizing' ) def lowerCamelCase ( self ): """simple docstring""" pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowerCamelCase ( self ): """simple docstring""" pass @require_torch class __UpperCAmelCase ( _lowerCamelCase ): @slow def lowerCamelCase ( self ): """simple docstring""" with torch.no_grad(): _snake_case = EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() _snake_case = torch.tensor([[0, 1, 2, 3, 4, 5]] ) _snake_case = model(lowerCAmelCase_ )[0] _snake_case = 33 _snake_case = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , lowerCAmelCase_ ) _snake_case = torch.tensor( [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) ) @slow def lowerCamelCase ( self ): """simple docstring""" with torch.no_grad(): _snake_case = EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) model.eval() _snake_case = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) _snake_case = model(lowerCAmelCase_ )[0] # compare the actual values for a slice. _snake_case = torch.tensor( [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) )
495
0
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
715
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Tuple , lowercase : pyspark.sql.DataFrame , lowercase : Optional[NamedSplit] = None , lowercase : Optional[Features] = None , lowercase : bool = True , lowercase : str = None , lowercase : bool = False , lowercase : str = None , lowercase : bool = True , lowercase : str = "arrow" , **lowercase : Any , ) -> Optional[int]: '''simple docstring''' super().__init__( split=lowercase , features=lowercase , cache_dir=lowercase , keep_in_memory=lowercase , streaming=lowercase , **lowercase , ) UpperCamelCase__ = load_from_cache_file UpperCamelCase__ = file_format UpperCamelCase__ = Spark( df=lowercase , features=lowercase , cache_dir=lowercase , working_dir=lowercase , **lowercase , ) def A ( self : int ) -> Any: '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) UpperCamelCase__ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
265
0
def __lowerCAmelCase ( _UpperCamelCase : int = 10 ) -> str: '''simple docstring''' if not isinstance(_UpperCamelCase , _UpperCamelCase ) or n < 0: raise ValueError('Invalid input' ) SCREAMING_SNAKE_CASE = 10**n SCREAMING_SNAKE_CASE = 2_84_33 * (pow(2 , 7_83_04_57 , _UpperCamelCase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
439
from __future__ import annotations from math import gcd def __lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int = 2 , _UpperCamelCase : int = 1 , _UpperCamelCase : int = 3 , ) -> int | None: '''simple docstring''' if num < 2: raise ValueError('The input value cannot be less than 2' ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(_UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : int ) -> int: return (pow(_UpperCamelCase , 2 ) + step) % modulus for _ in range(_UpperCamelCase ): # These track the position within the cycle detection logic. SCREAMING_SNAKE_CASE = seed SCREAMING_SNAKE_CASE = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. SCREAMING_SNAKE_CASE = rand_fn(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE = rand_fn(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE = rand_fn(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. SCREAMING_SNAKE_CASE = gcd(hare - tortoise , _UpperCamelCase ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. SCREAMING_SNAKE_CASE = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse a_ : int = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) a_ : Tuple = parser.parse_args() a_ : int = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(F"""{args.num} is probably prime""") else: a_ : Union[str, Any] = args.num // divisor print(F"""{args.num} = {divisor} * {quotient}""")
439
1
'''simple docstring''' from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
233
'''simple docstring''' import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __lowerCAmelCase: def __init__( self : List[str] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[int]=13 , SCREAMING_SNAKE_CASE : str=64 , SCREAMING_SNAKE_CASE : List[Any]=2 , SCREAMING_SNAKE_CASE : Any=3 , SCREAMING_SNAKE_CASE : Tuple=True , SCREAMING_SNAKE_CASE : List[str]=True , SCREAMING_SNAKE_CASE : Optional[Any]=32 , SCREAMING_SNAKE_CASE : Optional[int]=5 , SCREAMING_SNAKE_CASE : Dict=4 , SCREAMING_SNAKE_CASE : Optional[int]=37 , SCREAMING_SNAKE_CASE : int="gelu" , SCREAMING_SNAKE_CASE : int=0.1 , SCREAMING_SNAKE_CASE : int=0.1 , SCREAMING_SNAKE_CASE : List[Any]=10 , SCREAMING_SNAKE_CASE : Dict=0.02 , SCREAMING_SNAKE_CASE : str=[1, 16, 4, 4] , SCREAMING_SNAKE_CASE : int=None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ :str = parent SCREAMING_SNAKE_CASE_ :int = batch_size SCREAMING_SNAKE_CASE_ :Any = image_size SCREAMING_SNAKE_CASE_ :Tuple = patch_size SCREAMING_SNAKE_CASE_ :List[Any] = num_channels SCREAMING_SNAKE_CASE_ :Dict = is_training SCREAMING_SNAKE_CASE_ :Tuple = use_labels SCREAMING_SNAKE_CASE_ :List[Any] = hidden_size SCREAMING_SNAKE_CASE_ :Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ :Dict = num_attention_heads SCREAMING_SNAKE_CASE_ :Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ :Optional[Any] = hidden_act SCREAMING_SNAKE_CASE_ :Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ :Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ :List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ :Optional[int] = initializer_range SCREAMING_SNAKE_CASE_ :Dict = scope SCREAMING_SNAKE_CASE_ :Union[str, Any] = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size SCREAMING_SNAKE_CASE_ :List[str] = (self.image_size // 32) ** 2 SCREAMING_SNAKE_CASE_ :Optional[int] = num_patches + 1 def _lowercase ( self : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ :Optional[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE_ :Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ :Optional[int] = self.get_config() return config, pixel_values, labels def _lowercase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ :List[str] = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [4, 8, 16, 32], 'num_groups': 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=SCREAMING_SNAKE_CASE , ) def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[int] = ViTHybridModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE_ :List[str] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : str , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Union[str, Any] = self.type_sequence_label_size SCREAMING_SNAKE_CASE_ :Any = ViTHybridForImageClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE_ :int = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Tuple = config_and_inputs SCREAMING_SNAKE_CASE_ :Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): __snake_case : Dict = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () __snake_case : int = ( {'feature-extraction': ViTHybridModel, 'image-classification': ViTHybridForImageClassification} if is_torch_available() else {} ) __snake_case : Dict = False __snake_case : Union[str, Any] = False __snake_case : List[Any] = False def _lowercase ( self : Any ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Tuple = ViTHybridModelTester(self ) SCREAMING_SNAKE_CASE_ :List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def _lowercase ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds' ) def _lowercase ( self : str ): """simple docstring""" pass def _lowercase ( self : Union[str, Any] ): """simple docstring""" 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_ :Tuple = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE_ :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , nn.Linear ) ) def _lowercase ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ :int = model_class(SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ :List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ :List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ :int = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def _lowercase ( 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(*SCREAMING_SNAKE_CASE ) def _lowercase ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def _lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": SCREAMING_SNAKE_CASE_ :Any = [f'{name}.{key}' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @slow def _lowercase ( self : Dict ): """simple docstring""" for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ :Union[str, Any] = ViTHybridModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE_ :Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __lowerCAmelCase( unittest.TestCase ): @cached_property def _lowercase ( self : Optional[Any] ): """simple docstring""" return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _lowercase ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[int] = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ :int = self.default_image_processor SCREAMING_SNAKE_CASE_ :Dict = prepare_img() SCREAMING_SNAKE_CASE_ :str = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ :Union[str, Any] = model(**SCREAMING_SNAKE_CASE ) # verify the logits SCREAMING_SNAKE_CASE_ :Any = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ :Optional[Any] = torch.tensor([-1.90_90, -0.49_93, -0.23_89] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow @require_accelerate def _lowercase ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Tuple = ViTHybridImageProcessor.from_pretrained('google/vit-hybrid-base-bit-384' ) SCREAMING_SNAKE_CASE_ :List[Any] = ViTHybridForImageClassification.from_pretrained('google/vit-hybrid-base-bit-384' , device_map='auto' ) SCREAMING_SNAKE_CASE_ :Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE_ :Optional[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) SCREAMING_SNAKE_CASE_ :Optional[int] = model(**SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ :Any = outputs.logits # model predicts one of the 1000 ImageNet classes SCREAMING_SNAKE_CASE_ :int = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , 'tabby, tabby cat' )
233
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _SCREAMING_SNAKE_CASE = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _SCREAMING_SNAKE_CASE = { "vocab_file": { "google/electra-small-generator": ( "https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt" ), "google/electra-base-generator": "https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt", "google/electra-large-generator": ( "https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt" ), "google/electra-small-discriminator": ( "https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt" ), "google/electra-base-discriminator": ( "https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt" ), "google/electra-large-discriminator": ( "https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt" ), }, "tokenizer_file": { "google/electra-small-generator": ( "https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json" ), "google/electra-base-generator": ( "https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json" ), "google/electra-large-generator": ( "https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json" ), "google/electra-small-discriminator": ( "https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json" ), "google/electra-base-discriminator": ( "https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json" ), "google/electra-large-discriminator": ( "https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json" ), }, } _SCREAMING_SNAKE_CASE = { "google/electra-small-generator": 5_12, "google/electra-base-generator": 5_12, "google/electra-large-generator": 5_12, "google/electra-small-discriminator": 5_12, "google/electra-base-discriminator": 5_12, "google/electra-large-discriminator": 5_12, } _SCREAMING_SNAKE_CASE = { "google/electra-small-generator": {"do_lower_case": True}, "google/electra-base-generator": {"do_lower_case": True}, "google/electra-large-generator": {"do_lower_case": True}, "google/electra-small-discriminator": {"do_lower_case": True}, "google/electra-base-discriminator": {"do_lower_case": True}, "google/electra-large-discriminator": {"do_lower_case": True}, } class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : Dict = VOCAB_FILES_NAMES __lowerCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[str] = PRETRAINED_INIT_CONFIGURATION __lowerCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : List[Any] = ElectraTokenizer def __init__( self , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase="[UNK]" , _lowerCAmelCase="[SEP]" , _lowerCAmelCase="[PAD]" , _lowerCAmelCase="[CLS]" , _lowerCAmelCase="[MASK]" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ) -> List[Any]: super().__init__( _lowerCAmelCase , tokenizer_file=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , tokenize_chinese_chars=_lowerCAmelCase , strip_accents=_lowerCAmelCase , **_lowerCAmelCase , ) _lowerCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , _lowerCAmelCase ) != do_lower_case or normalizer_state.get("strip_accents" , _lowerCAmelCase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , _lowerCAmelCase ) != tokenize_chinese_chars ): _lowerCAmelCase = getattr(_lowerCAmelCase , normalizer_state.pop("type" ) ) _lowerCAmelCase = do_lower_case _lowerCAmelCase = strip_accents _lowerCAmelCase = tokenize_chinese_chars _lowerCAmelCase = normalizer_class(**_lowerCAmelCase ) _lowerCAmelCase = do_lower_case def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase=None ) -> str: _lowerCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None ) -> List[int]: _lowerCAmelCase = [self.sep_token_id] _lowerCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None ) -> Tuple[str]: _lowerCAmelCase = self._tokenizer.model.save(_lowerCAmelCase , name=_lowerCAmelCase ) return tuple(_lowerCAmelCase )
18
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _lowerCamelCase ( nn.Module ): def __init__( self : Optional[Any] ) -> Optional[int]: """simple docstring""" super().__init__() lowerCAmelCase__ : Optional[int] = nn.Linear(3 , 4 ) lowerCAmelCase__ : int = nn.BatchNormad(4 ) lowerCAmelCase__ : Optional[Any] = nn.Linear(4 , 5 ) def _lowerCAmelCase ( self : List[str] , UpperCamelCase : List[Any] ) -> Tuple: """simple docstring""" return self.lineara(self.batchnorm(self.lineara(UpperCamelCase ) ) ) class _lowerCamelCase ( unittest.TestCase ): def _lowerCAmelCase ( self : Any ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : Any = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , model.state_dict() ) lowerCAmelCase__ : List[str] = os.path.join(UpperCamelCase , """index.json""" ) self.assertTrue(os.path.isfile(UpperCamelCase ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: lowerCAmelCase__ : Tuple = os.path.join(UpperCamelCase , f"""{key}.dat""" ) self.assertTrue(os.path.isfile(UpperCamelCase ) ) # TODO: add tests on the fact weights are properly loaded def _lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" lowerCAmelCase__ : List[str] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: lowerCAmelCase__ : Union[str, Any] = torch.randn(2 , 3 , dtype=UpperCamelCase ) with TemporaryDirectory() as tmp_dir: lowerCAmelCase__ : Optional[Any] = offload_weight(UpperCamelCase , """weight""" , UpperCamelCase , {} ) lowerCAmelCase__ : Dict = os.path.join(UpperCamelCase , """weight.dat""" ) self.assertTrue(os.path.isfile(UpperCamelCase ) ) self.assertDictEqual(UpperCamelCase , {"""weight""": {"""shape""": [2, 3], """dtype""": str(UpperCamelCase ).split(""".""" )[1]}} ) lowerCAmelCase__ : Any = load_offloaded_weight(UpperCamelCase , index["""weight"""] ) self.assertTrue(torch.equal(UpperCamelCase , UpperCamelCase ) ) def _lowerCAmelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = ModelForTest() lowerCAmelCase__ : Optional[Any] = model.state_dict() lowerCAmelCase__ : Tuple = {k: v for k, v in state_dict.items() if """linear2""" not in k} lowerCAmelCase__ : Any = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : str = OffloadedWeightsLoader(state_dict=UpperCamelCase , save_folder=UpperCamelCase ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase , weight_map[key] ) ) lowerCAmelCase__ : str = {k: v for k, v in state_dict.items() if """weight""" in k} lowerCAmelCase__ : str = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Any = OffloadedWeightsLoader(state_dict=UpperCamelCase , save_folder=UpperCamelCase ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , UpperCamelCase ) # Duplicates are removed lowerCAmelCase__ : List[str] = OffloadedWeightsLoader(state_dict=UpperCamelCase , save_folder=UpperCamelCase ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase , weight_map[key] ) ) def _lowerCAmelCase ( self : Dict ) -> Any: """simple docstring""" lowerCAmelCase__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} lowerCAmelCase__ : Any = extract_submodules_state_dict(UpperCamelCase , ["""a.1""", """a.2"""] ) self.assertDictEqual(UpperCamelCase , {"""a.1""": 0, """a.2""": 2} ) lowerCAmelCase__ : str = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} lowerCAmelCase__ : Union[str, Any] = extract_submodules_state_dict(UpperCamelCase , ["""a.1""", """a.2"""] ) self.assertDictEqual(UpperCamelCase , {"""a.1.a""": 0, """a.2.a""": 2} )
299
0
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCamelCase_ = 'src/transformers' UpperCamelCase_ = 'docs/source/en' UpperCamelCase_ = '.' def _UpperCAmelCase ( A , A , A ): '''simple docstring''' with open(A , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCAmelCase__ =f.readlines() # Find the start prompt. UpperCAmelCase__ =0 while not lines[start_index].startswith(A ): start_index += 1 start_index += 1 UpperCAmelCase__ =start_index while not lines[end_index].startswith(A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCamelCase_ = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. UpperCamelCase_ = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') UpperCamelCase_ = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCamelCase_ = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. UpperCamelCase_ = direct_transformers_import(TRANSFORMERS_PATH) def _UpperCAmelCase ( A ): '''simple docstring''' UpperCAmelCase__ =re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" , A ) return [m.group(0 ) for m in matches] def _UpperCAmelCase ( A , A ): '''simple docstring''' UpperCAmelCase__ =2 if text == "✅" or text == "❌" else len(A ) UpperCAmelCase__ =(width - text_length) // 2 UpperCAmelCase__ =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _UpperCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES UpperCAmelCase__ ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } UpperCAmelCase__ ={name: config.replace("Config" , "" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. UpperCAmelCase__ =collections.defaultdict(A ) UpperCAmelCase__ =collections.defaultdict(A ) UpperCAmelCase__ =collections.defaultdict(A ) UpperCAmelCase__ =collections.defaultdict(A ) UpperCAmelCase__ =collections.defaultdict(A ) # Let's lookup through all transformers object (once). for attr_name in dir(A ): UpperCAmelCase__ =None if attr_name.endswith("Tokenizer" ): UpperCAmelCase__ =slow_tokenizers UpperCAmelCase__ =attr_name[:-9] elif attr_name.endswith("TokenizerFast" ): UpperCAmelCase__ =fast_tokenizers UpperCAmelCase__ =attr_name[:-13] elif _re_tf_models.match(A ) is not None: UpperCAmelCase__ =tf_models UpperCAmelCase__ =_re_tf_models.match(A ).groups()[0] elif _re_flax_models.match(A ) is not None: UpperCAmelCase__ =flax_models UpperCAmelCase__ =_re_flax_models.match(A ).groups()[0] elif _re_pt_models.match(A ) is not None: UpperCAmelCase__ =pt_models UpperCAmelCase__ =_re_pt_models.match(A ).groups()[0] if lookup_dict is not None: while len(A ) > 0: if attr_name in model_name_to_prefix.values(): UpperCAmelCase__ =True break # Try again after removing the last word in the name UpperCAmelCase__ ="".join(camel_case_split(A )[:-1] ) # Let's build that table! UpperCAmelCase__ =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) UpperCAmelCase__ =["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). UpperCAmelCase__ =[len(A ) + 2 for c in columns] UpperCAmelCase__ =max([len(A ) for name in model_names] ) + 2 # Build the table per se UpperCAmelCase__ ="|" + "|".join([_center_text(A , A ) for c, w in zip(A , A )] ) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n" UpperCAmelCase__ ={True: "✅", False: "❌"} for name in model_names: UpperCAmelCase__ =model_name_to_prefix[name] UpperCAmelCase__ =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(A , A ) for l, w in zip(A , A )] ) + "|\n" return table def _UpperCAmelCase ( A=False ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ =_find_text_in_file( filename=os.path.join(A , "index.md" ) , start_prompt="<!--This table is updated automatically from the auto modules" , end_prompt="<!-- End table-->" , ) UpperCAmelCase__ =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(A , "index.md" ) , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase_ = parser.parse_args() check_model_table(args.fix_and_overwrite)
510
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class snake_case_ : '''simple docstring''' __UpperCamelCase = None def __UpperCAmelCase ( self ) -> str: UpperCAmelCase__ =self.feature_extraction_class(**self.feat_extract_dict ) UpperCAmelCase__ =json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key], A_ ) def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase__ =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ =os.path.join(A_, "feat_extract.json" ) feat_extract_first.to_json_file(A_ ) UpperCAmelCase__ =self.feature_extraction_class.from_json_file(A_ ) self.assertEqual(feat_extract_second.to_dict(), feat_extract_first.to_dict() ) def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase__ =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ =feat_extract_first.save_pretrained(A_ )[0] check_json_file_has_correct_format(A_ ) UpperCAmelCase__ =self.feature_extraction_class.from_pretrained(A_ ) self.assertEqual(feat_extract_second.to_dict(), feat_extract_first.to_dict() ) def __UpperCAmelCase ( self ) -> str: UpperCAmelCase__ =self.feature_extraction_class() self.assertIsNotNone(A_ )
510
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __A : List[Any] , __A : Any=7 , __A : Optional[Any]=3 , __A : Any=3_0 , __A : Optional[Any]=4_0_0 , __A : Union[str, Any]=True , __A : int=None , __A : Union[str, Any]=True , __A : Tuple=1 / 2_5_5 , __A : str=True , __A : Tuple=[0.5, 0.5, 0.5] , __A : Optional[int]=[0.5, 0.5, 0.5] , __A : Tuple=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p snake_case__ : int = size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} snake_case__ : Union[str, Any] = parent snake_case__ : Optional[Any] = batch_size snake_case__ : Tuple = num_channels snake_case__ : Any = min_resolution snake_case__ : int = max_resolution snake_case__ : str = do_resize snake_case__ : Optional[int] = size snake_case__ : List[Any] = do_rescale snake_case__ : Optional[int] = rescale_factor snake_case__ : Optional[Any] = do_normalize snake_case__ : str = image_mean snake_case__ : Union[str, Any] = image_std snake_case__ : int = do_pad def _lowercase ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def _lowercase ( self : Optional[Any] , __A : Tuple , __A : int=False ): if not batched: snake_case__ : Optional[int] = image_inputs[0] if isinstance(snake_case__ , Image.Image ): snake_case__, snake_case__ : str = image.size else: snake_case__, snake_case__ : str = image.shape[1], image.shape[2] if w < h: snake_case__ : Optional[Any] = int(self.size["shortest_edge"] * h / w ) snake_case__ : Tuple = self.size["shortest_edge"] elif w > h: snake_case__ : Optional[Any] = self.size["shortest_edge"] snake_case__ : List[str] = int(self.size["shortest_edge"] * w / h ) else: snake_case__ : Optional[int] = self.size["shortest_edge"] snake_case__ : List[Any] = self.size["shortest_edge"] else: snake_case__ : Dict = [] for image in image_inputs: snake_case__, snake_case__ : Dict = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case__ : Tuple = max(snake_case__ , key=lambda __A : item[0] )[0] snake_case__ : str = max(snake_case__ , key=lambda __A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" a_ = DetrImageProcessor if is_vision_available() else None def _lowercase ( self : Dict ): snake_case__ : Any = DetrImageProcessingTester(self ) @property def _lowercase ( self : Dict ): return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self : Dict ): snake_case__ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case__ , "image_mean" ) ) self.assertTrue(hasattr(snake_case__ , "image_std" ) ) self.assertTrue(hasattr(snake_case__ , "do_normalize" ) ) self.assertTrue(hasattr(snake_case__ , "do_rescale" ) ) self.assertTrue(hasattr(snake_case__ , "rescale_factor" ) ) self.assertTrue(hasattr(snake_case__ , "do_resize" ) ) self.assertTrue(hasattr(snake_case__ , "size" ) ) self.assertTrue(hasattr(snake_case__ , "do_pad" ) ) def _lowercase ( self : List[str] ): snake_case__ : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , snake_case__ ) snake_case__ : List[str] = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=snake_case__ ) self.assertEqual(image_processor.size , {"shortest_edge": 4_2, "longest_edge": 8_4} ) self.assertEqual(image_processor.do_pad , snake_case__ ) def _lowercase ( self : int ): pass def _lowercase ( self : Union[str, Any] ): # Initialize image_processing snake_case__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , Image.Image ) # Test not batched input snake_case__ : str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : int = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__, snake_case__ : Any = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) snake_case__ : Any = image_processing(snake_case__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _lowercase ( self : List[str] ): # Initialize image_processing snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , np.ndarray ) # Test not batched input snake_case__ : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : Tuple = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ : Optional[Any] = image_processing(snake_case__ , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : Optional[Any] = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _lowercase ( self : Dict ): # Initialize image_processing snake_case__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , torchify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , torch.Tensor ) # Test not batched input snake_case__ : List[str] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : List[Any] = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ : str = image_processing(snake_case__ , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : Union[str, Any] = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _lowercase ( self : List[Any] ): # prepare image and target snake_case__ : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: snake_case__ : str = json.loads(f.read() ) snake_case__ : Any = {"image_id": 3_9_7_6_9, "annotations": target} # encode them snake_case__ : int = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50" ) snake_case__ : List[Any] = image_processing(images=snake_case__ , annotations=snake_case__ , return_tensors="pt" ) # verify pixel values snake_case__ : Any = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , snake_case__ ) snake_case__ : Optional[Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1e-4 ) ) # verify area snake_case__ : Optional[int] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case__ ) ) # verify boxes snake_case__ : int = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ ) snake_case__ : Optional[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1e-3 ) ) # verify image_id snake_case__ : List[str] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) ) # verify is_crowd snake_case__ : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) ) # verify class_labels snake_case__ : Union[str, Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) ) # verify orig_size snake_case__ : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) ) # verify size snake_case__ : Optional[Any] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) ) @slow def _lowercase ( self : Any ): # prepare image, target and masks_path snake_case__ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: snake_case__ : str = json.loads(f.read() ) snake_case__ : Union[str, Any] = {"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} snake_case__ : Optional[int] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them snake_case__ : List[str] = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic" ) snake_case__ : Any = image_processing(images=snake_case__ , annotations=snake_case__ , masks_path=snake_case__ , return_tensors="pt" ) # verify pixel values snake_case__ : Union[str, Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , snake_case__ ) snake_case__ : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1e-4 ) ) # verify area snake_case__ : Tuple = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case__ ) ) # verify boxes snake_case__ : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ ) snake_case__ : Optional[int] = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1e-3 ) ) # verify image_id snake_case__ : Optional[int] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) ) # verify is_crowd snake_case__ : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) ) # verify class_labels snake_case__ : Optional[int] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) ) # verify masks snake_case__ : Optional[int] = 8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , snake_case__ ) # verify orig_size snake_case__ : List[Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) ) # verify size snake_case__ : str = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) )
297
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Dict , snake_case__ : int , snake_case__ : int , snake_case__ : int , snake_case__ : Tuple=0.0 , snake_case__ : Optional[int] = None , snake_case__ : str = "geglu" , snake_case__ : Optional[int] = None , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = True , snake_case__ : str = "layer_norm" , snake_case__ : bool = False , ) -> Dict: super().__init__() _lowerCamelCase = only_cross_attention _lowerCamelCase = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' _lowerCamelCase = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" f""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _lowerCamelCase = AdaLayerNorm(snake_case__ , snake_case__ ) elif self.use_ada_layer_norm_zero: _lowerCamelCase = AdaLayerNormZero(snake_case__ , snake_case__ ) else: _lowerCamelCase = nn.LayerNorm(snake_case__ , elementwise_affine=snake_case__ ) _lowerCamelCase = Attention( query_dim=snake_case__ , heads=snake_case__ , dim_head=snake_case__ , dropout=snake_case__ , bias=snake_case__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=snake_case__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _lowerCamelCase = ( AdaLayerNorm(snake_case__ , snake_case__ ) if self.use_ada_layer_norm else nn.LayerNorm(snake_case__ , elementwise_affine=snake_case__ ) ) _lowerCamelCase = Attention( query_dim=snake_case__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=snake_case__ , dim_head=snake_case__ , dropout=snake_case__ , bias=snake_case__ , upcast_attention=snake_case__ , ) # is self-attn if encoder_hidden_states is none else: _lowerCamelCase = None _lowerCamelCase = None # 3. Feed-forward _lowerCamelCase = nn.LayerNorm(snake_case__ , elementwise_affine=snake_case__ ) _lowerCamelCase = FeedForward(snake_case__ , dropout=snake_case__ , activation_fn=snake_case__ , final_dropout=snake_case__ ) # let chunk size default to None _lowerCamelCase = None _lowerCamelCase = 0 def _snake_case ( self : str , snake_case__ : Optional[int] , snake_case__ : int ) -> Optional[Any]: # Sets chunk feed-forward _lowerCamelCase = chunk_size _lowerCamelCase = dim def _snake_case ( self : Union[str, Any] , snake_case__ : torch.FloatTensor , snake_case__ : Optional[torch.FloatTensor] = None , snake_case__ : Optional[torch.FloatTensor] = None , snake_case__ : Optional[torch.FloatTensor] = None , snake_case__ : Optional[torch.LongTensor] = None , snake_case__ : Dict[str, Any] = None , snake_case__ : Optional[torch.LongTensor] = None , ) -> List[Any]: # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: _lowerCamelCase = self.norma(snake_case__ , snake_case__ ) elif self.use_ada_layer_norm_zero: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = self.norma( snake_case__ , snake_case__ , snake_case__ , hidden_dtype=hidden_states.dtype ) else: _lowerCamelCase = self.norma(snake_case__ ) _lowerCamelCase = cross_attention_kwargs if cross_attention_kwargs is not None else {} _lowerCamelCase = self.attna( snake_case__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=snake_case__ , **snake_case__ , ) if self.use_ada_layer_norm_zero: _lowerCamelCase = gate_msa.unsqueeze(1 ) * attn_output _lowerCamelCase = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _lowerCamelCase = ( self.norma(snake_case__ , snake_case__ ) if self.use_ada_layer_norm else self.norma(snake_case__ ) ) _lowerCamelCase = self.attna( snake_case__ , encoder_hidden_states=snake_case__ , attention_mask=snake_case__ , **snake_case__ , ) _lowerCamelCase = attn_output + hidden_states # 3. Feed-forward _lowerCamelCase = self.norma(snake_case__ ) if self.use_ada_layer_norm_zero: _lowerCamelCase = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) _lowerCamelCase = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _lowerCamelCase = torch.cat( [self.ff(snake_case__ ) for hid_slice in norm_hidden_states.chunk(snake_case__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _lowerCamelCase = self.ff(snake_case__ ) if self.use_ada_layer_norm_zero: _lowerCamelCase = gate_mlp.unsqueeze(1 ) * ff_output _lowerCamelCase = ff_output + hidden_states return hidden_states class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Union[str, Any] , snake_case__ : int , snake_case__ : Optional[int] = None , snake_case__ : int = 4 , snake_case__ : float = 0.0 , snake_case__ : str = "geglu" , snake_case__ : bool = False , ) -> Optional[int]: super().__init__() _lowerCamelCase = int(dim * mult ) _lowerCamelCase = dim_out if dim_out is not None else dim if activation_fn == "gelu": _lowerCamelCase = GELU(snake_case__ , snake_case__ ) if activation_fn == "gelu-approximate": _lowerCamelCase = GELU(snake_case__ , snake_case__ , approximate='tanh' ) elif activation_fn == "geglu": _lowerCamelCase = GEGLU(snake_case__ , snake_case__ ) elif activation_fn == "geglu-approximate": _lowerCamelCase = ApproximateGELU(snake_case__ , snake_case__ ) _lowerCamelCase = nn.ModuleList([] ) # project in self.net.append(snake_case__ ) # project dropout self.net.append(nn.Dropout(snake_case__ ) ) # project out self.net.append(nn.Linear(snake_case__ , snake_case__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(snake_case__ ) ) def _snake_case ( self : Tuple , snake_case__ : List[Any] ) -> Optional[int]: for module in self.net: _lowerCamelCase = module(snake_case__ ) return hidden_states class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : str , snake_case__ : int , snake_case__ : int , snake_case__ : str = "none" ) -> Any: super().__init__() _lowerCamelCase = nn.Linear(snake_case__ , snake_case__ ) _lowerCamelCase = approximate def _snake_case ( self : List[Any] , snake_case__ : List[Any] ) -> int: if gate.device.type != "mps": return F.gelu(snake_case__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _snake_case ( self : Optional[int] , snake_case__ : Union[str, Any] ) -> str: _lowerCamelCase = self.proj(snake_case__ ) _lowerCamelCase = self.gelu(snake_case__ ) return hidden_states class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Dict , snake_case__ : int , snake_case__ : int ) -> List[Any]: super().__init__() _lowerCamelCase = nn.Linear(snake_case__ , dim_out * 2 ) def _snake_case ( self : Optional[Any] , snake_case__ : Optional[int] ) -> Optional[Any]: if gate.device.type != "mps": return F.gelu(snake_case__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _snake_case ( self : List[str] , snake_case__ : Optional[Any] ) -> Optional[int]: _lowerCamelCase , _lowerCamelCase = self.proj(snake_case__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(snake_case__ ) class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Dict , snake_case__ : int , snake_case__ : int ) -> Tuple: super().__init__() _lowerCamelCase = nn.Linear(snake_case__ , snake_case__ ) def _snake_case ( self : Optional[Any] , snake_case__ : List[Any] ) -> Optional[int]: _lowerCamelCase = self.proj(snake_case__ ) return x * torch.sigmoid(1.702 * x ) class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , snake_case__ : Tuple , snake_case__ : Any ) -> Dict: super().__init__() _lowerCamelCase = nn.Embedding(snake_case__ , snake_case__ ) _lowerCamelCase = nn.SiLU() _lowerCamelCase = nn.Linear(snake_case__ , embedding_dim * 2 ) _lowerCamelCase = nn.LayerNorm(snake_case__ , elementwise_affine=snake_case__ ) def _snake_case ( self : Tuple , snake_case__ : str , snake_case__ : Dict ) -> Optional[int]: _lowerCamelCase = self.linear(self.silu(self.emb(snake_case__ ) ) ) _lowerCamelCase , _lowerCamelCase = torch.chunk(snake_case__ , 2 ) _lowerCamelCase = self.norm(snake_case__ ) * (1 + scale) + shift return x class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Any , snake_case__ : Optional[Any] , snake_case__ : Union[str, Any] ) -> Dict: super().__init__() _lowerCamelCase = CombinedTimestepLabelEmbeddings(snake_case__ , snake_case__ ) _lowerCamelCase = nn.SiLU() _lowerCamelCase = nn.Linear(snake_case__ , 6 * embedding_dim , bias=snake_case__ ) _lowerCamelCase = nn.LayerNorm(snake_case__ , elementwise_affine=snake_case__ , eps=1e-6 ) def _snake_case ( self : Dict , snake_case__ : Tuple , snake_case__ : str , snake_case__ : str , snake_case__ : List[Any]=None ) -> int: _lowerCamelCase = self.linear(self.silu(self.emb(snake_case__ , snake_case__ , hidden_dtype=snake_case__ ) ) ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = emb.chunk(6 , dim=1 ) _lowerCamelCase = self.norm(snake_case__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class lowerCAmelCase__ ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , snake_case__ : int , snake_case__ : int , snake_case__ : int , snake_case__ : Optional[str] = None , snake_case__ : float = 1e-5 ) -> int: super().__init__() _lowerCamelCase = num_groups _lowerCamelCase = eps if act_fn is None: _lowerCamelCase = None else: _lowerCamelCase = get_activation(snake_case__ ) _lowerCamelCase = nn.Linear(snake_case__ , out_dim * 2 ) def _snake_case ( self : Union[str, Any] , snake_case__ : int , snake_case__ : Optional[Any] ) -> Union[str, Any]: if self.act: _lowerCamelCase = self.act(snake_case__ ) _lowerCamelCase = self.linear(snake_case__ ) _lowerCamelCase = emb[:, :, None, None] _lowerCamelCase , _lowerCamelCase = emb.chunk(2 , dim=1 ) _lowerCamelCase = F.group_norm(snake_case__ , self.num_groups , eps=self.eps ) _lowerCamelCase = x * (1 + scale) + shift return x
544
0
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class UpperCamelCase : def __init__( self , snake_case__ , snake_case__=14 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=False , snake_case__=True , snake_case__=99 , snake_case__=32 , snake_case__=4 , snake_case__=4 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=512 , snake_case__=0.02 , ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = parent _SCREAMING_SNAKE_CASE : List[Any] = batch_size _SCREAMING_SNAKE_CASE : Tuple = seq_length _SCREAMING_SNAKE_CASE : Dict = is_training _SCREAMING_SNAKE_CASE : Optional[Any] = use_input_mask _SCREAMING_SNAKE_CASE : Optional[int] = use_token_type_ids _SCREAMING_SNAKE_CASE : Any = use_labels _SCREAMING_SNAKE_CASE : List[str] = vocab_size _SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size _SCREAMING_SNAKE_CASE : Optional[Any] = rotary_dim _SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers _SCREAMING_SNAKE_CASE : Any = num_attention_heads _SCREAMING_SNAKE_CASE : int = intermediate_size _SCREAMING_SNAKE_CASE : int = hidden_act _SCREAMING_SNAKE_CASE : str = hidden_dropout_prob _SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings _SCREAMING_SNAKE_CASE : List[Any] = initializer_range _SCREAMING_SNAKE_CASE : Tuple = None _SCREAMING_SNAKE_CASE : str = vocab_size - 1 _SCREAMING_SNAKE_CASE : Dict = vocab_size - 1 _SCREAMING_SNAKE_CASE : Dict = vocab_size - 1 def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE : str = None if self.use_input_mask: _SCREAMING_SNAKE_CASE : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE : str = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=snake_case__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE : Optional[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : List[Any] = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = 20 _SCREAMING_SNAKE_CASE : List[str] = model_class_name(snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = model.init_cache(input_ids.shape[0] , snake_case__ ) _SCREAMING_SNAKE_CASE : int = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="i4" ) _SCREAMING_SNAKE_CASE : str = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) _SCREAMING_SNAKE_CASE : int = model( input_ids[:, :-1] , attention_mask=snake_case__ , past_key_values=snake_case__ , position_ids=snake_case__ , ) _SCREAMING_SNAKE_CASE : str = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4" ) _SCREAMING_SNAKE_CASE : Optional[Any] = model( input_ids[:, -1:] , attention_mask=snake_case__ , past_key_values=outputs_cache.past_key_values , position_ids=snake_case__ , ) _SCREAMING_SNAKE_CASE : Any = model(snake_case__ ) _SCREAMING_SNAKE_CASE : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F'''Max diff is {diff}''' ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = 20 _SCREAMING_SNAKE_CASE : Any = model_class_name(snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) _SCREAMING_SNAKE_CASE : int = model.init_cache(input_ids.shape[0] , snake_case__ ) _SCREAMING_SNAKE_CASE : Any = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) _SCREAMING_SNAKE_CASE : List[str] = model( input_ids[:, :-1] , attention_mask=snake_case__ , past_key_values=snake_case__ , position_ids=snake_case__ , ) _SCREAMING_SNAKE_CASE : Optional[int] = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4" ) _SCREAMING_SNAKE_CASE : Tuple = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=snake_case__ , position_ids=snake_case__ , ) _SCREAMING_SNAKE_CASE : Tuple = model(snake_case__ , attention_mask=snake_case__ ) _SCREAMING_SNAKE_CASE : List[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F'''Max diff is {diff}''' ) @require_flax class UpperCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): A__ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () A__ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = FlaxGPTJModelTester(self ) def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" for model_class_name in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" for model_class_name in self.all_model_classes: _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) @tooslow def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = GPTaTokenizer.from_pretrained("gpt2" , pad_token="<|endoftext|>" , padding_side="left" ) _SCREAMING_SNAKE_CASE : int = tokenizer(["Hello this is a long string", "Hey"] , return_tensors="np" , padding=snake_case__ , truncation=snake_case__ ) _SCREAMING_SNAKE_CASE : str = FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B" ) _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : List[str] = model.config.eos_token_id _SCREAMING_SNAKE_CASE : Any = jax.jit(model.generate ) _SCREAMING_SNAKE_CASE : Dict = jit_generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , pad_token_id=tokenizer.pad_token_id ).sequences _SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ ) _SCREAMING_SNAKE_CASE : Tuple = [ "Hello this is a long string of text.\n\nI'm trying to get the text of the", "Hey, I'm a little late to the party. I'm going to", ] self.assertListEqual(snake_case__ , snake_case__ ) @is_pt_flax_cross_test def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs _SCREAMING_SNAKE_CASE : Optional[int] = self._prepare_for_class(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class _SCREAMING_SNAKE_CASE : Optional[Any] = model_class.__name__[4:] # Skip the "Flax" at the beginning _SCREAMING_SNAKE_CASE : str = getattr(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE : str = pt_inputs["input_ids"].shape _SCREAMING_SNAKE_CASE : str = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(snake_case__ ): _SCREAMING_SNAKE_CASE : Tuple = 0 _SCREAMING_SNAKE_CASE : Any = 1 _SCREAMING_SNAKE_CASE : Tuple = 0 _SCREAMING_SNAKE_CASE : Optional[Any] = 1 _SCREAMING_SNAKE_CASE : List[Any] = pt_model_class(snake_case__ ).eval() _SCREAMING_SNAKE_CASE : Dict = model_class(snake_case__ , dtype=jnp.floataa ) _SCREAMING_SNAKE_CASE : Tuple = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = fx_state with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = pt_model(**snake_case__ ).to_tuple() _SCREAMING_SNAKE_CASE : Tuple = fx_model(**snake_case__ ).to_tuple() self.assertEqual(len(snake_case__ ) , len(snake_case__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(snake_case__ , snake_case__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(snake_case__ ) _SCREAMING_SNAKE_CASE : List[Any] = model_class.from_pretrained(snake_case__ , from_pt=snake_case__ ) _SCREAMING_SNAKE_CASE : Tuple = fx_model_loaded(**snake_case__ ).to_tuple() self.assertEqual( len(snake_case__ ) , len(snake_case__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output_loaded, pt_output in zip(snake_case__ , snake_case__ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs _SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE : str = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class _SCREAMING_SNAKE_CASE : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning _SCREAMING_SNAKE_CASE : List[Any] = getattr(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[int] = pt_model_class(snake_case__ ).eval() _SCREAMING_SNAKE_CASE : List[str] = model_class(snake_case__ , dtype=jnp.floataa ) _SCREAMING_SNAKE_CASE : int = load_flax_weights_in_pytorch_model(snake_case__ , fx_model.params ) _SCREAMING_SNAKE_CASE : str = pt_inputs["input_ids"].shape _SCREAMING_SNAKE_CASE : List[Any] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(snake_case__ ): _SCREAMING_SNAKE_CASE : List[str] = 0 _SCREAMING_SNAKE_CASE : List[Any] = 1 _SCREAMING_SNAKE_CASE : Optional[Any] = 0 _SCREAMING_SNAKE_CASE : str = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = pt_model(**snake_case__ ).to_tuple() _SCREAMING_SNAKE_CASE : List[str] = fx_model(**snake_case__ ).to_tuple() self.assertEqual(len(snake_case__ ) , len(snake_case__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(snake_case__ , snake_case__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(snake_case__ ) _SCREAMING_SNAKE_CASE : int = pt_model_class.from_pretrained(snake_case__ , from_flax=snake_case__ ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[int] = pt_model_loaded(**snake_case__ ).to_tuple() self.assertEqual( len(snake_case__ ) , len(snake_case__ ) , "Output lengths differ between Flax and PyTorch" ) for fx_output, pt_output in zip(snake_case__ , snake_case__ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" for model_class_name in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[Any] = model_class_name.from_pretrained("EleutherAI/gpt-j-6B" ) _SCREAMING_SNAKE_CASE : List[str] = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case__ )
713
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def _lowerCAmelCase ( lowerCamelCase__ : str ) -> Optional[int]: def decorator(lowerCamelCase__ : int ): _SCREAMING_SNAKE_CASE : Optional[int] = getattr(lowerCamelCase__, "handle_key", [] ) handle += [key] setattr(lowerCamelCase__, "handle_key", lowerCamelCase__ ) return func return decorator def _lowerCAmelCase ( *lowerCamelCase__ : List[str] ) -> Tuple: def decorator(lowerCamelCase__ : Dict ): _SCREAMING_SNAKE_CASE : List[Any] = getattr(lowerCamelCase__, "handle_key", [] ) handle += keys setattr(lowerCamelCase__, "handle_key", lowerCamelCase__ ) return func return decorator class UpperCamelCase ( __SCREAMING_SNAKE_CASE ): def __new__( cls , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = super().__new__(cls , snake_case__ , snake_case__ , snake_case__ ) if not hasattr(snake_case__ , "key_handler" ): setattr(snake_case__ , "key_handler" , {} ) setattr(snake_case__ , "handle_input" , KeyHandler.handle_input ) for value in attrs.values(): _SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(snake_case__ , "handle_key" , [] ) for key in handled_keys: _SCREAMING_SNAKE_CASE : Tuple = value return new_cls @staticmethod def __SCREAMING_SNAKE_CASE ( cls ): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = get_character() if char != KEYMAP["undefined"]: _SCREAMING_SNAKE_CASE : Dict = ord(snake_case__ ) _SCREAMING_SNAKE_CASE : Union[str, Any] = cls.key_handler.get(snake_case__ ) if handler: _SCREAMING_SNAKE_CASE : Optional[int] = char return handler(cls ) else: return None def _lowerCAmelCase ( cls : List[Any] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
295
0
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCAmelCase :Optional[int] = 16 _lowerCAmelCase :List[Any] = 32 def lowerCamelCase_ (UpperCamelCase__ : Accelerator , UpperCamelCase__ : int = 16 ): _UpperCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) _UpperCAmelCase : Any = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(UpperCamelCase__ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) _UpperCAmelCase : Optional[Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _UpperCAmelCase : Union[str, Any] = datasets.map( UpperCamelCase__ , batched=UpperCamelCase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _UpperCAmelCase : List[Any] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(UpperCamelCase__ : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. _UpperCAmelCase : Optional[Any] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _UpperCAmelCase : Tuple = 16 elif accelerator.mixed_precision != "no": _UpperCAmelCase : Any = 8 else: _UpperCAmelCase : int = None return tokenizer.pad( UpperCamelCase__ , padding='''longest''' , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors='''pt''' , ) # Instantiate dataloaders. _UpperCAmelCase : Union[str, Any] = DataLoader( tokenized_datasets['''train'''] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) _UpperCAmelCase : Optional[Any] = DataLoader( tokenized_datasets['''validation'''] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCAmelCase :Union[str, Any] = mocked_dataloaders # noqa: F811 def lowerCamelCase_ (UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[int] ): # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , UpperCamelCase__ ) == "1": _UpperCAmelCase : Any = 2 # New Code # _UpperCAmelCase : str = int(args.gradient_accumulation_steps ) # Initialize accelerator _UpperCAmelCase : Any = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=UpperCamelCase__ ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( '''Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`''' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _UpperCAmelCase : List[Any] = config['''lr'''] _UpperCAmelCase : Optional[int] = int(config['''num_epochs'''] ) _UpperCAmelCase : List[str] = int(config['''seed'''] ) _UpperCAmelCase : int = int(config['''batch_size'''] ) _UpperCAmelCase : Any = evaluate.load('''glue''' , '''mrpc''' ) set_seed(UpperCamelCase__ ) _UpperCAmelCase , _UpperCAmelCase : int = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _UpperCAmelCase : List[str] = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=UpperCamelCase__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _UpperCAmelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer _UpperCAmelCase : Tuple = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler _UpperCAmelCase : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : int = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(UpperCamelCase__ ): _UpperCAmelCase : List[str] = model(**UpperCamelCase__ ) _UpperCAmelCase : Tuple = output.loss accelerator.backward(UpperCamelCase__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _UpperCAmelCase : Any = model(**UpperCamelCase__ ) _UpperCAmelCase : List[Any] = outputs.logits.argmax(dim=-1 ) _UpperCAmelCase , _UpperCAmelCase : List[str] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) _UpperCAmelCase : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , UpperCamelCase__ ) def lowerCamelCase_ (): _UpperCAmelCase : List[Any] = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=UpperCamelCase__ , default=UpperCamelCase__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) # New Code # parser.add_argument( '''--gradient_accumulation_steps''' , type=UpperCamelCase__ , default=1 , help='''The number of minibatches to be ran before gradients are accumulated.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) _UpperCAmelCase : str = parser.parse_args() _UpperCAmelCase : int = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
506
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase :Any = logging.get_logger(__name__) _lowerCAmelCase :Union[str, Any] = { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json', } class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''lxmert''' a__ ={} def __init__( self , A=3_0_5_2_2 , A=7_6_8 , A=1_2 , A=9_5_0_0 , A=1_6_0_0 , A=4_0_0 , A=3_0_7_2 , A="gelu" , A=0.1 , A=0.1 , A=5_1_2 , A=2 , A=0.02 , A=1E-12 , A=9 , A=5 , A=5 , A=2_0_4_8 , A=4 , A=6.67 , A=True , A=True , A=True , A=True , A=True , A=True , A=True , **A , ) -> List[Any]: _UpperCAmelCase : int = vocab_size _UpperCAmelCase : str = hidden_size _UpperCAmelCase : str = num_attention_heads _UpperCAmelCase : str = hidden_act _UpperCAmelCase : Dict = intermediate_size _UpperCAmelCase : Union[str, Any] = hidden_dropout_prob _UpperCAmelCase : str = attention_probs_dropout_prob _UpperCAmelCase : Dict = max_position_embeddings _UpperCAmelCase : str = type_vocab_size _UpperCAmelCase : List[str] = initializer_range _UpperCAmelCase : List[str] = layer_norm_eps _UpperCAmelCase : Optional[int] = num_qa_labels _UpperCAmelCase : Tuple = num_object_labels _UpperCAmelCase : Optional[int] = num_attr_labels _UpperCAmelCase : List[str] = l_layers _UpperCAmelCase : Any = x_layers _UpperCAmelCase : Tuple = r_layers _UpperCAmelCase : Optional[Any] = visual_feat_dim _UpperCAmelCase : Optional[int] = visual_pos_dim _UpperCAmelCase : Optional[Any] = visual_loss_normalizer _UpperCAmelCase : int = task_matched _UpperCAmelCase : Optional[Any] = task_mask_lm _UpperCAmelCase : Union[str, Any] = task_obj_predict _UpperCAmelCase : Optional[int] = task_qa _UpperCAmelCase : Union[str, Any] = visual_obj_loss _UpperCAmelCase : List[str] = visual_attr_loss _UpperCAmelCase : Optional[int] = visual_feat_loss _UpperCAmelCase : Tuple = {'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers} super().__init__(**A )
506
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available A__ : str = { '''configuration_ernie''': ['''ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ErnieConfig''', '''ErnieOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] = [ '''ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ErnieForCausalLM''', '''ErnieForMaskedLM''', '''ErnieForMultipleChoice''', '''ErnieForNextSentencePrediction''', '''ErnieForPreTraining''', '''ErnieForQuestionAnswering''', '''ErnieForSequenceClassification''', '''ErnieForTokenClassification''', '''ErnieModel''', '''ErniePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys A__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
716
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class lowercase__ ( snake_case__ ): _UpperCAmelCase :torch.FloatTensor class lowercase__ ( snake_case__, snake_case__ ): @register_to_config def __init__( self : Any , snake_case__ : int = 3 , snake_case__ : int = 3 , snake_case__ : Tuple[str] = ("DownEncoderBlock2D",) , snake_case__ : Tuple[str] = ("UpDecoderBlock2D",) , snake_case__ : Tuple[int] = (64,) , snake_case__ : int = 1 , snake_case__ : str = "silu" , snake_case__ : int = 3 , snake_case__ : int = 32 , snake_case__ : int = 256 , snake_case__ : int = 32 , snake_case__ : Optional[int] = None , snake_case__ : float = 0.18_215 , snake_case__ : str = "group" , ): super().__init__() # pass init params to Encoder lowerCamelCase_ : Union[str, Any] =Encoder( in_channels=snake_case__ , out_channels=snake_case__ , down_block_types=snake_case__ , block_out_channels=snake_case__ , layers_per_block=snake_case__ , act_fn=snake_case__ , norm_num_groups=snake_case__ , double_z=snake_case__ , ) lowerCamelCase_ : Dict =vq_embed_dim if vq_embed_dim is not None else latent_channels lowerCamelCase_ : List[str] =nn.Convad(snake_case__ , snake_case__ , 1 ) lowerCamelCase_ : Optional[int] =VectorQuantizer(snake_case__ , snake_case__ , beta=0.25 , remap=snake_case__ , sane_index_shape=snake_case__ ) lowerCamelCase_ : List[str] =nn.Convad(snake_case__ , snake_case__ , 1 ) # pass init params to Decoder lowerCamelCase_ : Tuple =Decoder( in_channels=snake_case__ , out_channels=snake_case__ , up_block_types=snake_case__ , block_out_channels=snake_case__ , layers_per_block=snake_case__ , act_fn=snake_case__ , norm_num_groups=snake_case__ , norm_type=snake_case__ , ) @apply_forward_hook def UpperCAmelCase__ ( self : Optional[int] , snake_case__ : torch.FloatTensor , snake_case__ : bool = True ): lowerCamelCase_ : Optional[int] =self.encoder(snake_case__ ) lowerCamelCase_ : Dict =self.quant_conv(snake_case__ ) if not return_dict: return (h,) return VQEncoderOutput(latents=snake_case__ ) @apply_forward_hook def UpperCAmelCase__ ( self : Any , snake_case__ : torch.FloatTensor , snake_case__ : bool = False , snake_case__ : bool = True ): # also go through quantization layer if not force_not_quantize: lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ : int =self.quantize(snake_case__ ) else: lowerCamelCase_ : Optional[int] =h lowerCamelCase_ : Optional[Any] =self.post_quant_conv(snake_case__ ) lowerCamelCase_ : List[str] =self.decoder(snake_case__ , quant if self.config.norm_type == "spatial" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=snake_case__ ) def UpperCAmelCase__ ( self : List[Any] , snake_case__ : torch.FloatTensor , snake_case__ : bool = True ): lowerCamelCase_ : List[str] =sample lowerCamelCase_ : Any =self.encode(snake_case__ ).latents lowerCamelCase_ : List[Any] =self.decode(snake_case__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=snake_case__ )
244
0
from math import sqrt def lowercase_ (A : Union[str, Any] = 1_0_0_0_0_0_0 ): snake_case__ : int = 0 snake_case__ : int = 0 snake_case__ : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(lowercase_ , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(F"""{solution() = }""")
478
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '▁' _lowerCamelCase = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } _lowerCamelCase = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } _lowerCamelCase = { 'facebook/s2t-small-librispeech-asr': 1024, } _lowerCamelCase = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] _lowerCamelCase = {'mustc': MUSTC_LANGS} class __A ( lowerCamelCase__ ): """simple docstring""" UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = MAX_MODEL_INPUT_SIZES UpperCAmelCase__ = ["""input_ids""", """attention_mask"""] UpperCAmelCase__ = [] def __init__( self , a__ , a__ , a__="<s>" , a__="</s>" , a__="<pad>" , a__="<unk>" , a__=False , a__=False , a__=None , a__=None , a__ = None , **a__ , ): """simple docstring""" _lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=a__ , eos_token=a__ , unk_token=a__ , pad_token=a__ , do_upper_case=a__ , do_lower_case=a__ , tgt_lang=a__ , lang_codes=a__ , sp_model_kwargs=self.sp_model_kwargs , **a__ , ) _lowerCamelCase : Optional[int] = do_upper_case _lowerCamelCase : Optional[Any] = do_lower_case _lowerCamelCase : Tuple = load_json(a__) _lowerCamelCase : Union[str, Any] = {v: k for k, v in self.encoder.items()} _lowerCamelCase : Tuple = spm_file _lowerCamelCase : Any = load_spm(a__ , self.sp_model_kwargs) if lang_codes is not None: _lowerCamelCase : List[Any] = lang_codes _lowerCamelCase : List[str] = LANGUAGES[lang_codes] _lowerCamelCase : Any = [F"""<lang:{lang}>""" for lang in self.langs] _lowerCamelCase : Optional[Any] = {lang: self.sp_model.PieceToId(F"""<lang:{lang}>""") for lang in self.langs} _lowerCamelCase : List[str] = self.lang_tokens _lowerCamelCase : str = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang) else: _lowerCamelCase : Any = {} @property def __snake_case ( self): """simple docstring""" return len(self.encoder) @property def __snake_case ( self): """simple docstring""" return self._tgt_lang @tgt_lang.setter def __snake_case ( self , a__): """simple docstring""" _lowerCamelCase : Any = new_tgt_lang self.set_tgt_lang_special_tokens(a__) def __snake_case ( self , a__): """simple docstring""" _lowerCamelCase : Optional[Any] = self.lang_code_to_id[tgt_lang] _lowerCamelCase : Any = [lang_code_id] def __snake_case ( self , a__): """simple docstring""" return self.sp_model.encode(a__ , out_type=a__) def __snake_case ( self , a__): """simple docstring""" return self.encoder.get(a__ , self.encoder[self.unk_token]) def __snake_case ( self , a__): """simple docstring""" return self.decoder.get(a__ , self.unk_token) def __snake_case ( self , a__): """simple docstring""" _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _lowerCamelCase : List[Any] = self.sp_model.decode(a__) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _lowerCamelCase : Optional[int] = [] else: current_sub_tokens.append(a__) _lowerCamelCase : Tuple = self.sp_model.decode(a__) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def __snake_case ( self , a__ , a__=None): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id] def __snake_case ( self , a__ , a__ = None , a__ = False): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a__ , token_ids_a=a__ , already_has_special_tokens=a__) _lowerCamelCase : Tuple = [1] * len(self.prefix_tokens) _lowerCamelCase : Tuple = [1] if token_ids_a is None: return prefix_ones + ([0] * len(a__)) + suffix_ones return prefix_ones + ([0] * len(a__)) + ([0] * len(a__)) + suffix_ones def __snake_case ( self): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.encoder.copy() vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.__dict__.copy() _lowerCamelCase : str = None return state def __setstate__( self , a__): """simple docstring""" _lowerCamelCase : Optional[int] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): _lowerCamelCase : List[Any] = {} _lowerCamelCase : Dict = load_spm(self.spm_file , self.sp_model_kwargs) def __snake_case ( self , a__ , a__ = None): """simple docstring""" _lowerCamelCase : str = Path(a__) assert save_dir.is_dir(), F"""{save_directory} should be a directory""" _lowerCamelCase : Any = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) _lowerCamelCase : Optional[Any] = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , a__) if os.path.abspath(self.spm_file) != os.path.abspath(a__) and os.path.isfile(self.spm_file): copyfile(self.spm_file , a__) elif not os.path.isfile(self.spm_file): with open(a__ , '''wb''') as fi: _lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(a__) return (str(a__), str(a__)) def __UpperCAmelCase( lowercase_ , lowercase_ ): _lowerCamelCase : Optional[Any] = sentencepiece.SentencePieceProcessor(**lowercase_ ) spm.Load(str(lowercase_ ) ) return spm def __UpperCAmelCase( lowercase_ ): with open(lowercase_ , '''r''' ) as f: return json.load(lowercase_ ) def __UpperCAmelCase( lowercase_ , lowercase_ ): with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=2 )
114
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json''', } class _lowerCamelCase ( _lowercase ): UpperCAmelCase_ = "gpt_neox_japanese" def __init__(self , __a=3_20_00 , __a=25_60 , __a=32 , __a=32 , __a=4 , __a="gelu" , __a=1.00 , __a=1_00_00 , __a=20_48 , __a=0.02 , __a=1e-5 , __a=True , __a=3_19_96 , __a=3_19_99 , __a=0.1 , __a=0.0 , **__a , ) -> Optional[Any]: super().__init__(bos_token_id=__a , eos_token_id=__a , **__a ) UpperCamelCase = vocab_size UpperCamelCase = max_position_embeddings UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_multiple_size UpperCamelCase = hidden_act UpperCamelCase = rotary_pct UpperCamelCase = rotary_emb_base UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = use_cache UpperCamelCase = attention_dropout UpperCamelCase = hidden_dropout
544
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = 0 for ch in input_str: UpperCamelCase = ord(_SCREAMING_SNAKE_CASE ) UpperCamelCase = pow(2 , _SCREAMING_SNAKE_CASE ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
544
1
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = (EulerDiscreteScheduler,) __magic_name__ :Any = 10 def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = { 'num_train_timesteps': 1_1_0_0, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**__UpperCAmelCase ) return config def snake_case ( self ): '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] , [0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=__UpperCAmelCase , beta_end=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[Any] = self.scheduler_classes[0] lowerCAmelCase__ :int = self.get_scheduler_config() lowerCAmelCase__ :Optional[Any] = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ :str = torch.manual_seed(0 ) lowerCAmelCase__ :Tuple = self.dummy_model() lowerCAmelCase__ :Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ :List[Any] = sample.to(__UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ :Tuple = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Dict = model(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Any = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ) lowerCAmelCase__ :Any = output.prev_sample lowerCAmelCase__ :int = torch.sum(torch.abs(__UpperCAmelCase ) ) lowerCAmelCase__ :Union[str, Any] = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 10.08_07 ) < 1E-2 assert abs(result_mean.item() - 0.01_31 ) < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.scheduler_classes[0] lowerCAmelCase__ :Any = self.get_scheduler_config(prediction_type='v_prediction' ) lowerCAmelCase__ :int = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ :int = torch.manual_seed(0 ) lowerCAmelCase__ :int = self.dummy_model() lowerCAmelCase__ :Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ :Any = sample.to(__UpperCAmelCase ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ :List[Any] = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[Any] = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ) lowerCAmelCase__ :Any = output.prev_sample lowerCAmelCase__ :Tuple = torch.sum(torch.abs(__UpperCAmelCase ) ) lowerCAmelCase__ :Tuple = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 0.00_02 ) < 1E-2 assert abs(result_mean.item() - 2.2676E-06 ) < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = self.scheduler_classes[0] lowerCAmelCase__ :Tuple = self.get_scheduler_config() lowerCAmelCase__ :Dict = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps , device=__UpperCAmelCase ) lowerCAmelCase__ :int = torch.manual_seed(0 ) lowerCAmelCase__ :List[Any] = self.dummy_model() lowerCAmelCase__ :int = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() lowerCAmelCase__ :Dict = sample.to(__UpperCAmelCase ) for t in scheduler.timesteps: lowerCAmelCase__ :Optional[int] = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :List[str] = model(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ) lowerCAmelCase__ :List[str] = output.prev_sample lowerCAmelCase__ :Optional[int] = torch.sum(torch.abs(__UpperCAmelCase ) ) lowerCAmelCase__ :List[Any] = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 10.08_07 ) < 1E-2 assert abs(result_mean.item() - 0.01_31 ) < 1E-3 def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.scheduler_classes[0] lowerCAmelCase__ :str = self.get_scheduler_config() lowerCAmelCase__ :Optional[Any] = scheduler_class(**__UpperCAmelCase , use_karras_sigmas=__UpperCAmelCase ) scheduler.set_timesteps(self.num_inference_steps , device=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = torch.manual_seed(0 ) lowerCAmelCase__ :str = self.dummy_model() lowerCAmelCase__ :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() lowerCAmelCase__ :Tuple = sample.to(__UpperCAmelCase ) for t in scheduler.timesteps: lowerCAmelCase__ :Any = scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = model(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :int = scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , generator=__UpperCAmelCase ) lowerCAmelCase__ :Dict = output.prev_sample lowerCAmelCase__ :str = torch.sum(torch.abs(__UpperCAmelCase ) ) lowerCAmelCase__ :str = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 1_24.52_29_94_99_51_17_19 ) < 1E-2 assert abs(result_mean.item() - 0.1_62_13_93_26_33_39_99_63 ) < 1E-3
93
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType lowercase_ = logging.get_logger(__name__) lowercase_ = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off lowercase_ = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 1_0563, 1_0786, 1_1420, 1_1709, 1_1907, 1_3163, 1_3697, 1_3700, 1_4808, 1_5306, 1_6410, 1_6791, 1_7992, 1_9203, 1_9510, 2_0724, 2_2305, 2_2935, 2_7007, 3_0109, 3_0420, 3_3409, 3_4949, 4_0283, 4_0493, 4_0549, 4_7282, 4_9146, 5_0257, 5_0359, 5_0360, 5_0361 ] lowercase_ = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 1_0428, 1_0929, 1_1938, 1_2033, 1_2331, 1_2562, 1_3793, 1_4157, 1_4635, 1_5265, 1_5618, 1_6553, 1_6604, 1_8362, 1_8956, 2_0075, 2_1675, 2_2520, 2_6130, 2_6161, 2_6435, 2_8279, 2_9464, 3_1650, 3_2302, 3_2470, 3_6865, 4_2863, 4_7425, 4_9870, 5_0254, 5_0258, 5_0360, 5_0361, 5_0362 ] class _snake_case ( _UpperCamelCase): UpperCamelCase__ : List[Any] ="whisper" UpperCamelCase__ : Dict =["past_key_values"] UpperCamelCase__ : List[Any] ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Optional[Any], __lowercase : Dict=5_1865, __lowercase : Tuple=80, __lowercase : Optional[Any]=6, __lowercase : List[Any]=4, __lowercase : Any=6, __lowercase : Tuple=4, __lowercase : List[str]=1536, __lowercase : str=1536, __lowercase : Any=0.0, __lowercase : List[str]=0.0, __lowercase : Dict=5_0257, __lowercase : str=True, __lowercase : Optional[Any]=True, __lowercase : Optional[Any]="gelu", __lowercase : Optional[int]=256, __lowercase : List[Any]=0.0, __lowercase : Dict=0.0, __lowercase : List[Any]=0.0, __lowercase : int=0.02, __lowercase : Optional[Any]=False, __lowercase : Optional[Any]=1500, __lowercase : List[str]=448, __lowercase : Union[str, Any]=5_0256, __lowercase : List[str]=5_0256, __lowercase : Any=5_0256, __lowercase : str=None, __lowercase : List[Any]=[220, 5_0256], __lowercase : int=False, __lowercase : str=256, __lowercase : Any=False, __lowercase : Optional[Any]=0.05, __lowercase : Union[str, Any]=10, __lowercase : int=2, __lowercase : int=0.0, __lowercase : Optional[int]=10, __lowercase : str=0, __lowercase : Any=7, **__lowercase : Tuple, ): lowercase__ = vocab_size lowercase__ = num_mel_bins lowercase__ = d_model lowercase__ = encoder_layers lowercase__ = encoder_attention_heads lowercase__ = decoder_layers lowercase__ = decoder_attention_heads lowercase__ = decoder_ffn_dim lowercase__ = encoder_ffn_dim lowercase__ = dropout lowercase__ = attention_dropout lowercase__ = activation_dropout lowercase__ = activation_function lowercase__ = init_std lowercase__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = max_source_positions lowercase__ = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. lowercase__ = classifier_proj_size lowercase__ = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase__ = apply_spec_augment lowercase__ = mask_time_prob lowercase__ = mask_time_length lowercase__ = mask_time_min_masks lowercase__ = mask_feature_prob lowercase__ = mask_feature_length lowercase__ = mask_feature_min_masks lowercase__ = median_filter_width super().__init__( pad_token_id=__a, bos_token_id=__a, eos_token_id=__a, is_encoder_decoder=__a, decoder_start_token_id=__a, suppress_tokens=__a, begin_suppress_tokens=__a, **__a, ) class _snake_case ( _UpperCamelCase): @property def A__ ( self : Optional[int] ): lowercase__ = OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: lowercase__ = {0: "batch"} else: lowercase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__a, direction="inputs" ) return common_inputs def A__ ( self : Dict, __lowercase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"], __lowercase : int = -1, __lowercase : int = -1, __lowercase : bool = False, __lowercase : Optional["TensorType"] = None, __lowercase : int = 2_2050, __lowercase : float = 5.0, __lowercase : int = 220, ): lowercase__ = OrderedDict() lowercase__ = OnnxConfig.generate_dummy_inputs( self, preprocessor=preprocessor.feature_extractor, batch_size=__a, framework=__a, sampling_rate=__a, time_duration=__a, frequency=__a, ) lowercase__ = encoder_inputs["input_features"].shape[2] lowercase__ = encoder_sequence_length // 2 if self.use_past else seq_length lowercase__ = super().generate_dummy_inputs( preprocessor.tokenizer, __a, __a, __a, __a ) lowercase__ = encoder_inputs.pop("input_features" ) lowercase__ = decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: lowercase__ = decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def A__ ( self : str ): return 1e-3
706
import math def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(SCREAMING_SNAKE_CASE_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. lowercase_ = """Enter the base and the power separated by a comma: """ lowercase_ , lowercase_ = map(int, input(prompt).split(""",""")) lowercase_ , lowercase_ = map(int, input(prompt).split(""",""")) # We find the log of each number, using the function res(), which takes two # arguments. lowercase_ = res(xa, ya) lowercase_ = res(xa, ya) # We check for the largest number if resa > resa: print("""Largest number is""", xa, """^""", ya) elif resa > resa: print("""Largest number is""", xa, """^""", ya) else: print("""Both are equal""")
37
0
'''simple docstring''' import math def _snake_case ( A ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _snake_case ( A = 10001 ) -> int: try: lowerCAmelCase__ = int(A ) except (TypeError, ValueError): raise TypeError('''Parameter nth must be int or castable to int.''' ) from None if nth <= 0: raise ValueError('''Parameter nth must be greater than or equal to one.''' ) lowerCAmelCase__ = [] lowerCAmelCase__ = 2 while len(A ) < nth: if is_prime(A ): primes.append(A ) num += 1 else: num += 1 return primes[len(A ) - 1] if __name__ == "__main__": print(f"""{solution() = }""")
90
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowerCAmelCase__: int = datasets.logging.get_logger(__name__) lowerCAmelCase__: Optional[int] = "\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",\n author = \"Moosavi, Nafise Sadat and\n Strube, Michael\",\n booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",\n month = aug,\n year = \"2016\",\n address = \"Berlin, Germany\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/P16-1060\",\n doi = \"10.18653/v1/P16-1060\",\n pages = \"632--642\",\n}\n\n" lowerCAmelCase__: Any = "\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n" lowerCAmelCase__: Tuple = "\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting 'keep_singletons=False', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n 'mentions': mentions\n 'muc': MUC metric [Vilain et al, 1995]\n 'bcub': B-cubed [Bagga and Baldwin, 1998]\n 'ceafe': CEAFe [Luo et al., 2005]\n 'lea': LEA [Moosavi and Strube, 2016]\n 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric('coval')\n >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -',\n ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)',\n ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)',\n ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -',\n ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -',\n ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {'mentions/recall': 1.0,[...] 'conll_score': 100.0}\n" def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="dummy_doc" ) -> Tuple: SCREAMING_SNAKE_CASE_ : Dict = {doc: key_lines} SCREAMING_SNAKE_CASE_ : Dict = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : List[str] = {} SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = reader.get_doc_mentions(SCREAMING_SNAKE_CASE , key_doc_lines[doc] , SCREAMING_SNAKE_CASE ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : List[str] = reader.set_annotated_parse_trees(SCREAMING_SNAKE_CASE , key_doc_lines[doc] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(SCREAMING_SNAKE_CASE , sys_doc_lines[doc] , SCREAMING_SNAKE_CASE ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(SCREAMING_SNAKE_CASE , key_doc_lines[doc] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = reader.remove_nested_coref_mentions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = reader.remove_nested_coref_mentions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[int] = reader.get_mention_assignments(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : List[str] = reader.get_mention_assignments(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( 'Number of removed nested coreferring mentions in the key ' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( 'Number of resulting singleton clusters in the key ' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' 'files, respectively' ) return doc_coref_infos def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: SCREAMING_SNAKE_CASE_ : Optional[Any] = get_coref_infos(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluator.evaluate_documents(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 100:.2f}' , f' Precision: {precision * 100:.2f}' , f' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Dict = (conll / 3) * 100 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'conll_score': conll} ) return output_scores def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> int: SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('#' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Dict = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : int = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case_ ( datasets.Metric ): def __A ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' ) ), 'references': datasets.Sequence(datasets.Value('string' ) ), } ) , codebase_urls=['https://github.com/ns-moosavi/coval'] , reference_urls=[ 'https://github.com/ns-moosavi/coval', 'https://www.aclweb.org/anthology/P16-1060', 'http://www.conll.cemantix.org/2012/data.html', ] , ) def __A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=True , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=False ): SCREAMING_SNAKE_CASE_ : Any = [ ('mentions', evaluator.mentions), ('muc', evaluator.muc), ('bcub', evaluator.b_cubed), ('ceafe', evaluator.ceafe), ('lea', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Optional[int] = util.check_gold_parse_annotation(__lowerCAmelCase ) if not has_gold_parse: raise NotImplementedError('References should have gold parse annotation to use \'min_span\'.' ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=__lowerCAmelCase , sys_lines=__lowerCAmelCase , metrics=__lowerCAmelCase , NP_only=__lowerCAmelCase , remove_nested=__lowerCAmelCase , keep_singletons=__lowerCAmelCase , min_span=__lowerCAmelCase , ) return score
345
0
from __future__ import annotations from collections import Counter from random import random class _SCREAMING_SNAKE_CASE : def __init__( self ) -> Optional[int]: lowerCamelCase_ = {} def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Any: lowerCamelCase_ = {} def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> Dict: if nodea not in self.connections: self.add_node(UpperCamelCase__ ) if nodea not in self.connections: self.add_node(UpperCamelCase__ ) lowerCamelCase_ = probability def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: return list(self.connections ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> List[Any]: lowerCamelCase_ = 0 lowerCamelCase_ = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_ = Counter(graph.get_nodes() ) lowerCamelCase_ = start for _ in range(lowerCamelCase__ ): lowerCamelCase_ = graph.transition(lowerCamelCase__ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
711
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig __A =logging.get_logger(__name__) # General docstring __A ='''RegNetConfig''' # Base docstring __A ='''facebook/regnet-y-040''' __A =[1, 1_0_8_8, 7, 7] # Image classification docstring __A ='''facebook/regnet-y-040''' __A ='''tabby, tabby cat''' __A =[ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase = 3 , lowercase = 1 , lowercase = 1 , lowercase = "relu" , ) -> Dict: super().__init__() lowerCamelCase_ = nn.Convad( lowercase , lowercase , kernel_size=lowercase , stride=lowercase , padding=kernel_size // 2 , groups=lowercase , bias=lowercase , ) lowerCamelCase_ = nn.BatchNormad(lowercase ) lowerCamelCase_ = ACTaFN[activation] if activation is not None else nn.Identity() def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Optional[Any]: lowerCamelCase_ = self.convolution(lowercase ) lowerCamelCase_ = self.normalization(lowercase ) lowerCamelCase_ = self.activation(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase ) -> List[Any]: super().__init__() lowerCamelCase_ = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) lowerCamelCase_ = config.num_channels def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Union[str, Any]: lowerCamelCase_ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) lowerCamelCase_ = self.embedder(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase = 2 ) -> List[str]: super().__init__() lowerCamelCase_ = nn.Convad(lowercase , lowercase , kernel_size=1 , stride=lowercase , bias=lowercase ) lowerCamelCase_ = nn.BatchNormad(lowercase ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Tensor: lowerCamelCase_ = self.convolution(lowercase ) lowerCamelCase_ = self.normalization(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase ) -> List[Any]: super().__init__() lowerCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) lowerCamelCase_ = nn.Sequential( nn.Convad(lowercase , lowercase , kernel_size=1 ) , nn.ReLU() , nn.Convad(lowercase , lowercase , kernel_size=1 ) , nn.Sigmoid() , ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Union[str, Any]: # b c h w -> b c 1 1 lowerCamelCase_ = self.pooler(lowercase ) lowerCamelCase_ = self.attention(lowercase ) lowerCamelCase_ = hidden_state * attention return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase = 1 ) -> int: super().__init__() lowerCamelCase_ = in_channels != out_channels or stride != 1 lowerCamelCase_ = max(1 , out_channels // config.groups_width ) lowerCamelCase_ = ( RegNetShortCut(lowercase , lowercase , stride=lowercase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase_ = nn.Sequential( RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(lowercase , lowercase , stride=lowercase , groups=lowercase , activation=config.hidden_act ) , RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=lowercase ) , ) lowerCamelCase_ = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Dict: lowerCamelCase_ = hidden_state lowerCamelCase_ = self.layer(lowercase ) lowerCamelCase_ = self.shortcut(lowercase ) hidden_state += residual lowerCamelCase_ = self.activation(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase = 1 ) -> Dict: super().__init__() lowerCamelCase_ = in_channels != out_channels or stride != 1 lowerCamelCase_ = max(1 , out_channels // config.groups_width ) lowerCamelCase_ = ( RegNetShortCut(lowercase , lowercase , stride=lowercase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase_ = nn.Sequential( RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(lowercase , lowercase , stride=lowercase , groups=lowercase , activation=config.hidden_act ) , RegNetSELayer(lowercase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=lowercase ) , ) lowerCamelCase_ = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_( self , lowercase ) -> List[str]: lowerCamelCase_ = hidden_state lowerCamelCase_ = self.layer(lowercase ) lowerCamelCase_ = self.shortcut(lowercase ) hidden_state += residual lowerCamelCase_ = self.activation(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase = 2 , lowercase = 2 , ) -> Optional[int]: super().__init__() lowerCamelCase_ = RegNetXLayer if config.layer_type == "x" else RegNetYLayer lowerCamelCase_ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( lowercase , lowercase , lowercase , stride=lowercase , ) , *[layer(lowercase , lowercase , lowercase ) for _ in range(depth - 1 )] , ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> int: lowerCamelCase_ = self.layers(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase ) -> int: super().__init__() lowerCamelCase_ = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowerCamelCase_ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(lowercase , config.depths[1:] ): self.stages.append(RegNetStage(lowercase , lowercase , lowercase , depth=lowercase ) ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = False , lowercase = True ) -> BaseModelOutputWithNoAttention: lowerCamelCase_ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCamelCase_ = hidden_states + (hidden_state,) lowerCamelCase_ = stage_module(lowercase ) if output_hidden_states: lowerCamelCase_ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=lowercase , hidden_states=lowercase ) class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = RegNetConfig lowerCAmelCase__ = 'regnet' lowerCAmelCase__ = 'pixel_values' lowerCAmelCase__ = True def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Any: if isinstance(lowercase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="fan_out" , nonlinearity="relu" ) elif isinstance(lowercase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=False ) -> Any: if isinstance(lowercase , lowercase ): lowerCamelCase_ = value __A =R''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' __A =R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , snake_case_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class _SCREAMING_SNAKE_CASE ( snake_case_ ): def __init__( self , lowercase ) -> List[str]: super().__init__(lowercase ) lowerCamelCase_ = config lowerCamelCase_ = RegNetEmbeddings(lowercase ) lowerCamelCase_ = RegNetEncoder(lowercase ) lowerCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=lowercase , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = None , lowercase = None ) -> BaseModelOutputWithPoolingAndNoAttention: lowerCamelCase_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.embedder(lowercase ) lowerCamelCase_ = self.encoder( lowercase , output_hidden_states=lowercase , return_dict=lowercase ) lowerCamelCase_ = encoder_outputs[0] lowerCamelCase_ = self.pooler(lowercase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=lowercase , pooler_output=lowercase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , snake_case_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class _SCREAMING_SNAKE_CASE ( snake_case_ ): def __init__( self , lowercase ) -> Any: super().__init__(lowercase ) lowerCamelCase_ = config.num_labels lowerCamelCase_ = RegNetModel(lowercase ) # classification head lowerCamelCase_ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def SCREAMING_SNAKE_CASE_( self , lowercase = None , lowercase = None , lowercase = None , lowercase = None , ) -> ImageClassifierOutputWithNoAttention: lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.regnet(lowercase , output_hidden_states=lowercase , return_dict=lowercase ) lowerCamelCase_ = outputs.pooler_output if return_dict else outputs[1] lowerCamelCase_ = self.classifier(lowercase ) lowerCamelCase_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCamelCase_ = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCamelCase_ = "single_label_classification" else: lowerCamelCase_ = "multi_label_classification" if self.config.problem_type == "regression": lowerCamelCase_ = MSELoss() if self.num_labels == 1: lowerCamelCase_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowerCamelCase_ = loss_fct(lowercase , lowercase ) elif self.config.problem_type == "single_label_classification": lowerCamelCase_ = CrossEntropyLoss() lowerCamelCase_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCamelCase_ = BCEWithLogitsLoss() lowerCamelCase_ = loss_fct(lowercase , lowercase ) if not return_dict: lowerCamelCase_ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowercase , logits=lowercase , hidden_states=outputs.hidden_states )
313
0
'''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] ={ '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 SCREAMING_SNAKE_CASE_: Optional[Any] ={value: key for key, value in MORSE_CODE_DICT.items()} def lowerCAmelCase_ ( snake_case_ : str ) -> str: '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def lowerCAmelCase_ ( snake_case_ : str ) -> str: '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase_ = "Morse code here!" print(snake_case_ ) UpperCAmelCase_ = encrypt(snake_case_ ) print(snake_case_ ) UpperCAmelCase_ = decrypt(snake_case_ ) print(snake_case_ ) if __name__ == "__main__": main()
78
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def A_ ( a , a ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = checkpoint SCREAMING_SNAKE_CASE_ : Optional[Any] = {} SCREAMING_SNAKE_CASE_ : Any = vae_state_dict['encoder.conv_in.weight'] SCREAMING_SNAKE_CASE_ : str = vae_state_dict['encoder.conv_in.bias'] SCREAMING_SNAKE_CASE_ : Dict = vae_state_dict['encoder.conv_out.weight'] SCREAMING_SNAKE_CASE_ : List[str] = vae_state_dict['encoder.conv_out.bias'] SCREAMING_SNAKE_CASE_ : Tuple = vae_state_dict['encoder.norm_out.weight'] SCREAMING_SNAKE_CASE_ : Union[str, Any] = vae_state_dict['encoder.norm_out.bias'] SCREAMING_SNAKE_CASE_ : Any = vae_state_dict['decoder.conv_in.weight'] SCREAMING_SNAKE_CASE_ : Optional[Any] = vae_state_dict['decoder.conv_in.bias'] SCREAMING_SNAKE_CASE_ : Optional[Any] = vae_state_dict['decoder.conv_out.weight'] SCREAMING_SNAKE_CASE_ : Any = vae_state_dict['decoder.conv_out.bias'] SCREAMING_SNAKE_CASE_ : List[Any] = vae_state_dict['decoder.norm_out.weight'] SCREAMING_SNAKE_CASE_ : List[Any] = vae_state_dict['decoder.norm_out.bias'] SCREAMING_SNAKE_CASE_ : List[Any] = vae_state_dict['quant_conv.weight'] SCREAMING_SNAKE_CASE_ : List[str] = vae_state_dict['quant_conv.bias'] SCREAMING_SNAKE_CASE_ : str = vae_state_dict['post_quant_conv.weight'] SCREAMING_SNAKE_CASE_ : str = vae_state_dict['post_quant_conv.bias'] # Retrieves the keys for the encoder down blocks only SCREAMING_SNAKE_CASE_ : List[Any] = len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'encoder.down' in layer} ) SCREAMING_SNAKE_CASE_ : Optional[Any] = { layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(a ) } # Retrieves the keys for the decoder up blocks only SCREAMING_SNAKE_CASE_ : Optional[Any] = len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'decoder.up' in layer} ) SCREAMING_SNAKE_CASE_ : int = { layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(a ) } for i in range(a ): SCREAMING_SNAKE_CASE_ : int = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key] if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict: SCREAMING_SNAKE_CASE_ : List[str] = vae_state_dict.pop( f"encoder.down.{i}.downsample.conv.weight" ) SCREAMING_SNAKE_CASE_ : Dict = vae_state_dict.pop( f"encoder.down.{i}.downsample.conv.bias" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = renew_vae_resnet_paths(a ) SCREAMING_SNAKE_CASE_ : Any = {'old': f"down.{i}.block", 'new': f"down_blocks.{i}.resnets"} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) SCREAMING_SNAKE_CASE_ : Any = [key for key in vae_state_dict if 'encoder.mid.block' in key] SCREAMING_SNAKE_CASE_ : List[str] = 2 for i in range(1 , num_mid_res_blocks + 1 ): SCREAMING_SNAKE_CASE_ : str = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key] SCREAMING_SNAKE_CASE_ : Tuple = renew_vae_resnet_paths(a ) SCREAMING_SNAKE_CASE_ : List[str] = {'old': f"mid.block_{i}", 'new': f"mid_block.resnets.{i - 1}"} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) SCREAMING_SNAKE_CASE_ : List[str] = [key for key in vae_state_dict if 'encoder.mid.attn' in key] SCREAMING_SNAKE_CASE_ : List[Any] = renew_vae_attention_paths(a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) for i in range(a ): SCREAMING_SNAKE_CASE_ : Any = num_up_blocks - 1 - i SCREAMING_SNAKE_CASE_ : List[Any] = [ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key ] if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict: SCREAMING_SNAKE_CASE_ : List[Any] = vae_state_dict[ f"decoder.up.{block_id}.upsample.conv.weight" ] SCREAMING_SNAKE_CASE_ : Union[str, Any] = vae_state_dict[ f"decoder.up.{block_id}.upsample.conv.bias" ] SCREAMING_SNAKE_CASE_ : int = renew_vae_resnet_paths(a ) SCREAMING_SNAKE_CASE_ : str = {'old': f"up.{block_id}.block", 'new': f"up_blocks.{i}.resnets"} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) SCREAMING_SNAKE_CASE_ : Optional[int] = [key for key in vae_state_dict if 'decoder.mid.block' in key] SCREAMING_SNAKE_CASE_ : Union[str, Any] = 2 for i in range(1 , num_mid_res_blocks + 1 ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key] SCREAMING_SNAKE_CASE_ : Any = renew_vae_resnet_paths(a ) SCREAMING_SNAKE_CASE_ : int = {'old': f"mid.block_{i}", 'new': f"mid_block.resnets.{i - 1}"} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) SCREAMING_SNAKE_CASE_ : int = [key for key in vae_state_dict if 'decoder.mid.attn' in key] SCREAMING_SNAKE_CASE_ : List[Any] = renew_vae_attention_paths(a ) SCREAMING_SNAKE_CASE_ : List[Any] = {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) return new_checkpoint def A_ ( a , a , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = requests.get( ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml' ) SCREAMING_SNAKE_CASE_ : str = io.BytesIO(r.content ) SCREAMING_SNAKE_CASE_ : Dict = OmegaConf.load(a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 5_1_2 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'cuda' if torch.cuda.is_available() else 'cpu' if checkpoint_path.endswith('safetensors' ): from safetensors import safe_open SCREAMING_SNAKE_CASE_ : Tuple = {} with safe_open(a , framework='pt' , device='cpu' ) as f: for key in f.keys(): SCREAMING_SNAKE_CASE_ : int = f.get_tensor(a ) else: SCREAMING_SNAKE_CASE_ : List[str] = torch.load(a , map_location=a )['state_dict'] # Convert the VAE model. SCREAMING_SNAKE_CASE_ : List[Any] = create_vae_diffusers_config(a , image_size=a ) SCREAMING_SNAKE_CASE_ : int = custom_convert_ldm_vae_checkpoint(a , a ) SCREAMING_SNAKE_CASE_ : List[str] = AutoencoderKL(**a ) vae.load_state_dict(a ) vae.save_pretrained(a ) if __name__ == "__main__": lowerCAmelCase : Any = argparse.ArgumentParser() parser.add_argument('--vae_pt_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.') parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.') lowerCAmelCase : Dict = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
511
0
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer __a : List[str] = logging.get_logger(__name__) __a : int = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } __a : List[Any] = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } __a : Union[str, Any] = { 'facebook/blenderbot_small-90M': 512, } class _SCREAMING_SNAKE_CASE ( __snake_case ): """simple docstring""" _SCREAMING_SNAKE_CASE =VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE =PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE =BlenderbotSmallTokenizer def __init__( self: List[Any] , __A: List[Any]=None , __A: List[str]=None , __A: Tuple="<|endoftext|>" , __A: str="<|endoftext|>" , __A: List[str]="<|endoftext|>" , __A: Tuple=False , __A: Union[str, Any]=True , **__A: Optional[Any] , ): '''simple docstring''' super().__init__( ByteLevelBPETokenizer( vocab=__A , merges=__A , add_prefix_space=__A , trim_offsets=__A , ) , bos_token=__A , eos_token=__A , unk_token=__A , **__A , ) a__ = add_prefix_space def lowercase ( self: Tuple , __A: str , __A: Union[str, Any]=None ): '''simple docstring''' a__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase ( self: Any , __A: List[int] , __A: Optional[List[int]] = None ): '''simple docstring''' a__ = [self.sep_token_id] a__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
200
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __a : str = logging.get_logger(__name__) __a : Dict = { 'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json', 'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json', 'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json', 'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json', 'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json', 'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json', 'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json', 'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json', 'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json', 'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( __snake_case ): """simple docstring""" _SCREAMING_SNAKE_CASE ='xlm' _SCREAMING_SNAKE_CASE ={ 'hidden_size': 'emb_dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', 'n_words': 'vocab_size', # For backward compatibility } def __init__( self: Optional[Any] , __A: str=30145 , __A: Union[str, Any]=2048 , __A: Union[str, Any]=12 , __A: List[Any]=16 , __A: List[Any]=0.1 , __A: int=0.1 , __A: str=True , __A: int=False , __A: Optional[int]=False , __A: Union[str, Any]=False , __A: List[Any]=1 , __A: Dict=True , __A: List[Any]=512 , __A: Optional[int]=2048**-0.5 , __A: Tuple=1e-12 , __A: Optional[int]=0.0_2 , __A: Optional[int]=0 , __A: Union[str, Any]=1 , __A: List[Any]=2 , __A: Union[str, Any]=3 , __A: Tuple=5 , __A: Tuple=True , __A: Dict="first" , __A: Optional[int]=True , __A: int=None , __A: Optional[Any]=True , __A: Dict=0.1 , __A: Tuple=5 , __A: Union[str, Any]=5 , __A: Tuple=0 , __A: List[str]=0 , __A: int=2 , __A: Optional[int]=0 , **__A: Union[str, Any] , ): '''simple docstring''' a__ = vocab_size a__ = emb_dim a__ = n_layers a__ = n_heads a__ = dropout a__ = attention_dropout a__ = gelu_activation a__ = sinusoidal_embeddings a__ = causal a__ = asm a__ = n_langs a__ = use_lang_emb a__ = layer_norm_eps a__ = bos_index a__ = eos_index a__ = pad_index a__ = unk_index a__ = mask_index a__ = is_encoder a__ = max_position_embeddings a__ = embed_init_std a__ = init_std a__ = summary_type a__ = summary_use_proj a__ = summary_activation a__ = summary_proj_to_labels a__ = summary_first_dropout a__ = start_n_top a__ = end_n_top a__ = mask_token_id a__ = lang_id if "n_words" in kwargs: a__ = kwargs['''n_words'''] super().__init__(pad_token_id=__A , bos_token_id=__A , **__A ) class _SCREAMING_SNAKE_CASE ( __snake_case ): """simple docstring""" @property def lowercase ( self: int ): '''simple docstring''' if self.task == "multiple-choice": a__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: a__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
200
1
'''simple docstring''' import os import sys import unittest UpperCamelCase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) UpperCamelCase_ = os.path.join("""tests""", """models""", """bert""", """test_modeling_bert.py""") UpperCamelCase_ = os.path.join("""tests""", """models""", """blip""", """test_modeling_blip.py""") class a_ (unittest.TestCase ): def __UpperCamelCase ( self ): _lowerCAmelCase : str = get_test_to_tester_mapping(snake_case_ ) _lowerCAmelCase : str = get_test_to_tester_mapping(snake_case_ ) _lowerCAmelCase : Optional[Any] = {"""BertModelTest""": """BertModelTester"""} _lowerCAmelCase : Union[str, Any] = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(snake_case_ ) , snake_case_ ) self.assertEqual(get_test_info.to_json(snake_case_ ) , snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : Optional[Any] = get_model_to_test_mapping(snake_case_ ) _lowerCAmelCase : List[str] = get_model_to_test_mapping(snake_case_ ) _lowerCAmelCase : Union[str, Any] = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } _lowerCAmelCase : str = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(snake_case_ ) , snake_case_ ) self.assertEqual(get_test_info.to_json(snake_case_ ) , snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : Any = get_model_to_tester_mapping(snake_case_ ) _lowerCAmelCase : str = get_model_to_tester_mapping(snake_case_ ) _lowerCAmelCase : List[str] = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } _lowerCAmelCase : int = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(snake_case_ ) , snake_case_ ) self.assertEqual(get_test_info.to_json(snake_case_ ) , snake_case_ )
384
'''simple docstring''' import os from datetime import datetime as dt from github import Github UpperCamelCase_ = [ """good first issue""", """good second issue""", """good difficult issue""", """enhancement""", """new pipeline/model""", """new scheduler""", """wip""", ] def _UpperCAmelCase ( ) -> List[Any]: _lowerCAmelCase : Dict = Github(os.environ["""GITHUB_TOKEN"""] ) _lowerCAmelCase : Any = g.get_repo("""huggingface/diffusers""" ) _lowerCAmelCase : Tuple = repo.get_issues(state="""open""" ) for issue in open_issues: _lowerCAmelCase : Union[str, Any] = sorted(issue.get_comments() , key=lambda _lowerCamelCase : i.created_at , reverse=_lowerCamelCase ) _lowerCAmelCase : List[Any] = comments[0] if len(_lowerCamelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
384
1
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int a_ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class snake_case ( datasets.BuilderConfig): __UpperCamelCase = None def a__ ( __lowercase , __lowercase , ) -> str: import pyspark def generate_fn(): _A = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: _A = df_with_partition_id.select("*" ).where(f"""part_id = {partition_id}""" ).drop("part_id" ) _A = partition_df.collect() _A = 0 for row in rows: yield f"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class snake_case ( _BaseExamplesIterable): def __init__( self : int , a__ : "pyspark.sql.DataFrame" , a__ : Optional[int]=None , ) -> str: '''simple docstring''' _A = df _A = partition_order or range(self.df.rdd.getNumPartitions() ) _A = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' yield from self.generate_examples_fn() def a_ ( self : Optional[int] , a__ : np.random.Generator ) -> int: '''simple docstring''' _A = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(lowercase_ ) return SparkExamplesIterable(self.df , partition_order=lowercase_ ) def a_ ( self : Optional[int] , a__ : int , a__ : int ) -> int: '''simple docstring''' _A = self.split_shard_indices_by_worker(lowercase_ , lowercase_ ) return SparkExamplesIterable(self.df , partition_order=lowercase_ ) @property def a_ ( self : List[str] ) -> Dict: '''simple docstring''' return len(self.partition_order ) class snake_case ( datasets.DatasetBuilder): __UpperCamelCase = SparkConfig def __init__( self : Tuple , a__ : "pyspark.sql.DataFrame" , a__ : str = None , a__ : str = None , **a__ : str , ) -> str: '''simple docstring''' import pyspark _A = pyspark.sql.SparkSession.builder.getOrCreate() _A = df _A = working_dir super().__init__( cache_dir=lowercase_ , config_name=str(self.df.semanticHash() ) , **lowercase_ , ) def a_ ( self : str ) -> Any: '''simple docstring''' def create_cache_and_write_probe(a__ : str ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=lowercase_ ) _A = os.path.join(self._cache_dir , "fs_test" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(lowercase_ , "a" ) return [probe_file] if self._spark.conf.get("spark.master" , "" ).startswith("local" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: _A = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(lowercase_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def a_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def a_ ( self : List[Any] , a__ : datasets.download.download_manager.DownloadManager ) -> Union[str, Any]: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def a_ ( self : List[str] , a__ : Union[str, Any] ) -> str: '''simple docstring''' import pyspark def get_arrow_batch_size(a__ : Any ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) _A = self.df.count() _A = df_num_rows if df_num_rows <= 1_00 else 1_00 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. _A = ( self.df.limit(lowercase_ ) .repartition(1 ) .mapInArrow(lowercase_ , "batch_bytes: long" ) .agg(pyspark.sql.functions.sum("batch_bytes" ).alias("sample_bytes" ) ) .collect()[0] .sample_bytes / sample_num_rows ) _A = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. _A = min(lowercase_ , int(approx_total_size / max_shard_size ) ) _A = self.df.repartition(lowercase_ ) def a_ ( self : Any , a__ : str , a__ : str , a__ : int , ) -> Any: '''simple docstring''' import pyspark _A = ParquetWriter if file_format == """parquet""" else ArrowWriter _A = os.path.join(self._working_dir , os.path.basename(lowercase_ ) ) if self._working_dir else fpath _A = file_format == """parquet""" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. _A = self.config.features _A = self._writer_batch_size _A = self._fs.storage_options def write_arrow(a__ : str ): # Within the same SparkContext, no two task attempts will share the same attempt ID. _A = pyspark.TaskContext().taskAttemptId() _A = next(lowercase_ , lowercase_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["task_id", "num_examples", "num_bytes"] , ) _A = 0 _A = writer_class( features=lowercase_ , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=lowercase_ , storage_options=lowercase_ , embed_local_files=lowercase_ , ) _A = pa.Table.from_batches([first_batch] ) writer.write_table(lowercase_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: _A = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) shard_id += 1 _A = writer_class( features=writer._features , path=working_fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , writer_batch_size=lowercase_ , storage_options=lowercase_ , embed_local_files=lowercase_ , ) _A = pa.Table.from_batches([batch] ) writer.write_table(lowercase_ ) if writer._num_bytes > 0: _A = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["task_id", "num_examples", "num_bytes"] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(lowercase_ ) ): _A = os.path.join(os.path.dirname(lowercase_ ) , os.path.basename(lowercase_ ) ) shutil.move(lowercase_ , lowercase_ ) _A = ( self.df.mapInArrow(lowercase_ , "task_id: long, num_examples: long, num_bytes: long" ) .groupBy("task_id" ) .agg( pyspark.sql.functions.sum("num_examples" ).alias("total_num_examples" ) , pyspark.sql.functions.sum("num_bytes" ).alias("total_num_bytes" ) , pyspark.sql.functions.count("num_bytes" ).alias("num_shards" ) , pyspark.sql.functions.collect_list("num_examples" ).alias("shard_lengths" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def a_ ( self : Dict , a__ : "datasets.SplitGenerator" , a__ : str = "arrow" , a__ : Optional[Union[str, int]] = None , a__ : Optional[int] = None , **a__ : List[str] , ) -> Union[str, Any]: '''simple docstring''' self._validate_cache_dir() _A = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(lowercase_ ) _A = not is_remote_filesystem(self._fs ) _A = os.path.join if is_local else posixpath.join _A = """-TTTTT-SSSSS-of-NNNNN""" _A = F"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" _A = path_join(self._output_dir , lowercase_ ) _A = 0 _A = 0 _A = 0 _A = [] _A = [] for task_id, content in self._prepare_split_single(lowercase_ , lowercase_ , lowercase_ ): ( _A ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(lowercase_ ) _A = total_num_examples _A = total_num_bytes # should rename everything at the end logger.debug(F"""Renaming {total_shards} shards.""" ) if total_shards > 1: _A = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. _A = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( a__ : int , a__ : int , a__ : int , ): rename( lowercase_ , fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace("TTTTT-SSSSS" , F"""{global_shard_id:05d}""" ).replace("NNNNN" , F"""{total_shards:05d}""" ) , ) _A = [] _A = 0 for i in range(len(lowercase_ ) ): _A = task_id_and_num_shards[i] for shard_id in range(lowercase_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(lowercase_ , len(lowercase_ ) ).map(lambda a__ : _rename_shard(*lowercase_ ) ).collect() else: # don't use any pattern _A = 0 _A = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS" , F"""{shard_id:05d}""" ).replace("TTTTT" , F"""{task_id:05d}""" ) , fpath.replace(lowercase_ , "" ) , ) def a_ ( self : Union[str, Any] , a__ : "datasets.SplitGenerator" , ) -> Any: '''simple docstring''' return SparkExamplesIterable(self.df )
708
"""simple docstring""" from __future__ import annotations def a__ ( __lowercase , __lowercase ) -> float: _A = sorted(numsa + numsa ) _A , _A = divmod(len(__lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() a_ = [float(x) for x in input("Enter the elements of first array: ").split()] a_ = [float(x) for x in input("Enter the elements of second array: ").split()] print(f'''The median of two arrays is: {median_of_two_arrays(array_a, array_a)}''')
621
0
def lowercase ( __A : List[Any] ) -> int: '''simple docstring''' if not isinstance(A__ , A__ ): snake_case : Optional[Any] = f"""Input value of [number={number}] must be an integer""" raise TypeError(A__ ) if number < 1: snake_case : str = f"""Input value of [number={number}] must be > 0""" raise ValueError(A__ ) snake_case : Optional[Any] = 1 for i in range(1 , A__ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
36
'''simple docstring''' import os lowercase : Tuple = {'I': 1, 'V': 5, 'X': 1_0, 'L': 5_0, 'C': 1_0_0, 'D': 5_0_0, 'M': 1_0_0_0} def __a ( A__ ) -> int: lowerCAmelCase = 0 lowerCAmelCase = 0 while index < len(A__ ) - 1: lowerCAmelCase = SYMBOLS[numerals[index]] lowerCAmelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def __a ( A__ ) -> str: lowerCAmelCase = "" lowerCAmelCase = num // 1000 numerals += m_count * "M" num %= 1000 lowerCAmelCase = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 lowerCAmelCase = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def __a ( A__ = "/p089_roman.txt" ) -> int: lowerCAmelCase = 0 with open(os.path.dirname(A__ ) + roman_numerals_filename ) as filea: lowerCAmelCase = filea.readlines() for line in lines: lowerCAmelCase = line.strip() lowerCAmelCase = parse_roman_numerals(A__ ) lowerCAmelCase = generate_roman_numerals(A__ ) savings += len(A__ ) - len(A__ ) return savings if __name__ == "__main__": print(f"{solution() = }")
649
0
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : int = logging.getLogger(__name__) @dataclass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[float] =field( default=0.0 ,metadata={"""help""": """The label smoothing epsilon to apply (if not zero)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """Whether to SortishSamler or not."""} ) __UpperCAmelCase : bool =field( default=lowerCAmelCase__ ,metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """whether to use adafactor"""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Encoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Decoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field(default=lowerCAmelCase__ ,metadata={"""help""": """Dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Attention dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[str] =field( default="""linear""" ,metadata={"""help""": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} ,)
282
"""simple docstring""" import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging A : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , __a , __a=7_68 ): super().__init__(__a ) __lowerCAmelCase = proj_size __lowerCAmelCase = CLIPVisionModel(__a ) __lowerCAmelCase = PaintByExampleMapper(__a ) __lowerCAmelCase = nn.LayerNorm(config.hidden_size ) __lowerCAmelCase = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling __lowerCAmelCase = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def snake_case ( self , __a , __a=False ): __lowerCAmelCase = self.model(pixel_values=__a ) __lowerCAmelCase = clip_output.pooler_output __lowerCAmelCase = self.mapper(latent_states[:, None] ) __lowerCAmelCase = self.final_layer_norm(__a ) __lowerCAmelCase = self.proj_out(__a ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCAmelCase = (config.num_hidden_layers + 1) // 5 __lowerCAmelCase = config.hidden_size __lowerCAmelCase = 1 __lowerCAmelCase = nn.ModuleList( [ BasicTransformerBlock(__a , __a , __a , activation_fn="gelu" , attention_bias=__a ) for _ in range(__a ) ] ) def snake_case ( self , __a ): for block in self.blocks: __lowerCAmelCase = block(__a ) return hidden_states
282
1
import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() snake_case__ : Tuple = logging.get_logger(__name__) def __lowerCamelCase ( A__ : Union[str, Any] ) -> Tuple: lowerCamelCase_ : int = OrderedDict() for key, value in state_dict.items(): if key.startswith("""module.encoder""" ): lowerCamelCase_ : Tuple = key.replace("""module.encoder""" , """glpn.encoder""" ) if key.startswith("""module.decoder""" ): lowerCamelCase_ : str = key.replace("""module.decoder""" , """decoder.stages""" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 lowerCamelCase_ : List[Any] = key[key.find("""patch_embed""" ) + len("""patch_embed""" )] lowerCamelCase_ : List[str] = key.replace(f'''patch_embed{idx}''' , f'''patch_embeddings.{int(A__ )-1}''' ) if "norm" in key: lowerCamelCase_ : str = key.replace("""norm""" , """layer_norm""" ) if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 lowerCamelCase_ : List[Any] = key[key.find("""glpn.encoder.layer_norm""" ) + len("""glpn.encoder.layer_norm""" )] lowerCamelCase_ : Any = key.replace(f'''layer_norm{idx}''' , f'''layer_norm.{int(A__ )-1}''' ) if "layer_norm1" in key: lowerCamelCase_ : Dict = key.replace("""layer_norm1""" , """layer_norm_1""" ) if "layer_norm2" in key: lowerCamelCase_ : Optional[Any] = key.replace("""layer_norm2""" , """layer_norm_2""" ) if "block" in key: # replace for example block1 by block.0 lowerCamelCase_ : int = key[key.find("""block""" ) + len("""block""" )] lowerCamelCase_ : List[Any] = key.replace(f'''block{idx}''' , f'''block.{int(A__ )-1}''' ) if "attn.q" in key: lowerCamelCase_ : Union[str, Any] = key.replace("""attn.q""" , """attention.self.query""" ) if "attn.proj" in key: lowerCamelCase_ : Optional[Any] = key.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in key: lowerCamelCase_ : str = key.replace("""attn""" , """attention.self""" ) if "fc1" in key: lowerCamelCase_ : List[Any] = key.replace("""fc1""" , """dense1""" ) if "fc2" in key: lowerCamelCase_ : List[str] = key.replace("""fc2""" , """dense2""" ) if "linear_pred" in key: lowerCamelCase_ : Dict = key.replace("""linear_pred""" , """classifier""" ) if "linear_fuse" in key: lowerCamelCase_ : int = key.replace("""linear_fuse.conv""" , """linear_fuse""" ) lowerCamelCase_ : str = key.replace("""linear_fuse.bn""" , """batch_norm""" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 lowerCamelCase_ : List[Any] = key[key.find("""linear_c""" ) + len("""linear_c""" )] lowerCamelCase_ : Dict = key.replace(f'''linear_c{idx}''' , f'''linear_c.{int(A__ )-1}''' ) if "bot_conv" in key: lowerCamelCase_ : Optional[Any] = key.replace("""bot_conv""" , """0.convolution""" ) if "skip_conv1" in key: lowerCamelCase_ : List[Any] = key.replace("""skip_conv1""" , """1.convolution""" ) if "skip_conv2" in key: lowerCamelCase_ : Union[str, Any] = key.replace("""skip_conv2""" , """2.convolution""" ) if "fusion1" in key: lowerCamelCase_ : str = key.replace("""fusion1""" , """1.fusion""" ) if "fusion2" in key: lowerCamelCase_ : Any = key.replace("""fusion2""" , """2.fusion""" ) if "fusion3" in key: lowerCamelCase_ : Dict = key.replace("""fusion3""" , """3.fusion""" ) if "fusion" in key and "conv" in key: lowerCamelCase_ : Optional[Any] = key.replace("""conv""" , """convolutional_layer""" ) if key.startswith("""module.last_layer_depth""" ): lowerCamelCase_ : List[Any] = key.replace("""module.last_layer_depth""" , """head.head""" ) lowerCamelCase_ : Dict = value return new_state_dict def __lowerCamelCase ( A__ : Optional[Any] , A__ : List[Any] ) -> List[str]: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) lowerCamelCase_ : Tuple = state_dict.pop(f'''glpn.encoder.block.{i}.{j}.attention.self.kv.weight''' ) lowerCamelCase_ : Optional[int] = state_dict.pop(f'''glpn.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict lowerCamelCase_ : Any = kv_weight[ : config.hidden_sizes[i], : ] lowerCamelCase_ : Optional[Any] = kv_bias[: config.hidden_sizes[i]] lowerCamelCase_ : Optional[Any] = kv_weight[ config.hidden_sizes[i] :, : ] lowerCamelCase_ : Dict = kv_bias[config.hidden_sizes[i] :] def __lowerCamelCase ( ) -> Dict: lowerCamelCase_ : Optional[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowerCamelCase_ : List[str] = Image.open(requests.get(A__ , stream=A__ ).raw ) return image @torch.no_grad() def __lowerCamelCase ( A__ : Union[str, Any] , A__ : Optional[int] , A__ : int=False , A__ : List[Any]=None ) -> str: lowerCamelCase_ : Any = GLPNConfig(hidden_sizes=[64, 128, 320, 512] , decoder_hidden_size=64 , depths=[3, 8, 27, 3] ) # load image processor (only resize + rescale) lowerCamelCase_ : str = GLPNImageProcessor() # prepare image lowerCamelCase_ : List[str] = prepare_img() lowerCamelCase_ : List[Any] = image_processor(images=A__ , return_tensors="""pt""" ).pixel_values logger.info("""Converting model...""" ) # load original state dict lowerCamelCase_ : Optional[int] = torch.load(A__ , map_location=torch.device("""cpu""" ) ) # rename keys lowerCamelCase_ : List[Any] = rename_keys(A__ ) # key and value matrices need special treatment read_in_k_v(A__ , A__ ) # create HuggingFace model and load state dict lowerCamelCase_ : int = GLPNForDepthEstimation(A__ ) model.load_state_dict(A__ ) model.eval() # forward pass lowerCamelCase_ : Any = model(A__ ) lowerCamelCase_ : List[str] = outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: lowerCamelCase_ : Union[str, Any] = torch.tensor( [[4.4147, 4.0873, 4.0673], [3.7890, 3.2881, 3.1525], [3.7674, 3.5423, 3.4913]] ) elif "kitti" in model_name: lowerCamelCase_ : Optional[int] = torch.tensor( [[3.4291, 2.7865, 2.5151], [3.2841, 2.7021, 2.3502], [3.1147, 2.4625, 2.2481]] ) else: raise ValueError(f'''Unknown model name: {model_name}''' ) lowerCamelCase_ : Tuple = torch.Size([1, 480, 640] ) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , A__ , atol=1e-4 ) print("""Looks ok!""" ) # finally, push to hub if required if push_to_hub: logger.info("""Pushing model and image processor to the hub...""" ) model.push_to_hub( repo_path_or_name=Path(A__ , A__ ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=A__ , ) image_processor.push_to_hub( repo_path_or_name=Path(A__ , A__ ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=A__ , ) if __name__ == "__main__": snake_case__ : str = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) parser.add_argument( '--model_name', default='glpn-kitti', type=str, help='Name of the model in case you\'re pushing to the hub.', ) snake_case__ : Any = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
278
snake_case__ : List[Any] = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] snake_case__ : Tuple = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] snake_case__ : List[Any] = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] snake_case__ : List[str] = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] snake_case__ : Any = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] snake_case__ : int = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] snake_case__ : Any = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] snake_case__ : Union[str, Any] = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
278
1
"""simple docstring""" import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {name: getattr(transformers, name + """Fast""") for name in SLOW_TO_FAST_CONVERTERS} def A( snake_case_ , snake_case_ , snake_case_ , snake_case_ ): """simple docstring""" if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F"""Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.""" ) if tokenizer_name is None: lowercase__: str = TOKENIZER_CLASSES else: lowercase__: Optional[Any] = {tokenizer_name: getattr(snake_case_ , tokenizer_name + "Fast" )} logger.info(F"""Loading tokenizer classes: {tokenizer_names}""" ) for tokenizer_name in tokenizer_names: lowercase__: Union[str, Any] = TOKENIZER_CLASSES[tokenizer_name] lowercase__: Tuple = True if checkpoint_name is None: lowercase__: List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: lowercase__: Any = [checkpoint_name] logger.info(F"""For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}""" ) for checkpoint in checkpoint_names: logger.info(F"""Loading {tokenizer_class.__class__.__name__} {checkpoint}""" ) # Load tokenizer lowercase__: Tuple = tokenizer_class.from_pretrained(snake_case_ , force_download=snake_case_ ) # Save fast tokenizer logger.info(F"""Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}""" ) # For organization names we create sub-directories if "/" in checkpoint: lowercase__: Optional[Any] = checkpoint.split("/" ) lowercase__: Dict = os.path.join(snake_case_ , snake_case_ ) elif add_prefix: lowercase__: Tuple = checkpoint lowercase__: Any = dump_path else: lowercase__: List[Any] = None lowercase__: int = dump_path logger.info(F"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}""" ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: lowercase__: List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] lowercase__: Union[str, Any] = file_path.split(snake_case_ )[-1][0] if next_char == "/": lowercase__: Any = os.path.join(snake_case_ , snake_case_ ) lowercase__: str = None logger.info(F"""=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}""" ) lowercase__: List[str] = tokenizer.save_pretrained( snake_case_ , legacy_format=snake_case_ , filename_prefix=snake_case_ ) logger.info(F"""=> File names {file_names}""" ) for file_name in file_names: if not file_name.endswith("tokenizer.json" ): os.remove(snake_case_ ) logger.info(F"""=> removing {file_name}""" ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output generated fast tokenizer files.""" ) parser.add_argument( """--tokenizer_name""", default=None, type=str, help=( F"Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will " """download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--checkpoint_name""", default=None, type=str, help="""Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.""", ) parser.add_argument( """--force_download""", action="""store_true""", help="""Re-download checkpoints.""", ) UpperCamelCase = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
716
"""simple docstring""" from ..utils import DummyObject, requires_backends class _a ( metaclass=lowercase_ ): '''simple docstring''' UpperCamelCase__ = ["""torch""", """transformers""", """onnx"""] def __init__( self , *UpperCAmelCase_ , **UpperCAmelCase_) -> str: '''simple docstring''' requires_backends(self , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> List[Any]: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> Tuple: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) class _a ( metaclass=lowercase_ ): '''simple docstring''' UpperCamelCase__ = ["""torch""", """transformers""", """onnx"""] def __init__( self , *UpperCAmelCase_ , **UpperCAmelCase_) -> Optional[Any]: '''simple docstring''' requires_backends(self , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> int: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) class _a ( metaclass=lowercase_ ): '''simple docstring''' UpperCamelCase__ = ["""torch""", """transformers""", """onnx"""] def __init__( self , *UpperCAmelCase_ , **UpperCAmelCase_) -> int: '''simple docstring''' requires_backends(self , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> Any: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> int: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) class _a ( metaclass=lowercase_ ): '''simple docstring''' UpperCamelCase__ = ["""torch""", """transformers""", """onnx"""] def __init__( self , *UpperCAmelCase_ , **UpperCAmelCase_) -> Tuple: '''simple docstring''' requires_backends(self , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> str: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) class _a ( metaclass=lowercase_ ): '''simple docstring''' UpperCamelCase__ = ["""torch""", """transformers""", """onnx"""] def __init__( self , *UpperCAmelCase_ , **UpperCAmelCase_) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> List[str]: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) class _a ( metaclass=lowercase_ ): '''simple docstring''' UpperCamelCase__ = ["""torch""", """transformers""", """onnx"""] def __init__( self , *UpperCAmelCase_ , **UpperCAmelCase_) -> str: '''simple docstring''' requires_backends(self , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> List[str]: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"]) @classmethod def __lowercase ( cls , *UpperCAmelCase_ , **UpperCAmelCase_) -> str: '''simple docstring''' requires_backends(cls , ["torch", "transformers", "onnx"])
120
0
"""simple docstring""" import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class SCREAMING_SNAKE_CASE ( __lowerCamelCase ): """simple docstring""" def __init__( self : Union[str, Any] , _snake_case : UNetaDModel , _snake_case : UNetaDModel , _snake_case : DDPMScheduler , _snake_case : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__() a__ = value_function a__ = unet a__ = scheduler a__ = env a__ = env.get_dataset() a__ = {} for key in self.data.keys(): try: a__ = self.data[key].mean() except: # noqa: E722 pass a__ = {} for key in self.data.keys(): try: a__ = self.data[key].std() except: # noqa: E722 pass a__ = env.observation_space.shape[0] a__ = env.action_space.shape[0] def _lowerCAmelCase ( self : int , _snake_case : Union[str, Any] , _snake_case : Tuple ) -> str: '''simple docstring''' return (x_in - self.means[key]) / self.stds[key] def _lowerCAmelCase ( self : Any , _snake_case : Optional[Any] , _snake_case : str ) -> List[Any]: '''simple docstring''' return x_in * self.stds[key] + self.means[key] def _lowerCAmelCase ( self : int , _snake_case : List[Any] ) -> Any: '''simple docstring''' if type(__lowerCamelCase ) is dict: return {k: self.to_torch(__lowerCamelCase ) for k, v in x_in.items()} elif torch.is_tensor(__lowerCamelCase ): return x_in.to(self.unet.device ) return torch.tensor(__lowerCamelCase , device=self.unet.device ) def _lowerCAmelCase ( self : List[str] , _snake_case : str , _snake_case : Any , _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' for key, val in cond.items(): a__ = val.clone() return x_in def _lowerCAmelCase ( self : Union[str, Any] , _snake_case : Tuple , _snake_case : Any , _snake_case : Optional[Any] , _snake_case : Any ) -> Optional[Any]: '''simple docstring''' a__ = x.shape[0] a__ = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model a__ = torch.full((batch_size,) , __lowerCamelCase , device=self.unet.device , dtype=torch.long ) for _ in range(__lowerCamelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models a__ = self.value_function(x.permute(0 , 2 , 1 ) , __lowerCamelCase ).sample a__ = torch.autograd.grad([y.sum()] , [x] )[0] a__ = self.scheduler._get_variance(__lowerCamelCase ) a__ = torch.exp(0.5 * posterior_variance ) a__ = model_std * grad a__ = 0 a__ = x.detach() a__ = x + scale * grad a__ = self.reset_xa(__lowerCamelCase , __lowerCamelCase , self.action_dim ) a__ = self.unet(x.permute(0 , 2 , 1 ) , __lowerCamelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg a__ = self.scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , predict_epsilon=__lowerCamelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) a__ = self.reset_xa(__lowerCamelCase , __lowerCamelCase , self.action_dim ) a__ = self.to_torch(__lowerCamelCase ) return x, y def __call__( self : Union[str, Any] , _snake_case : Optional[int] , _snake_case : Optional[int]=64 , _snake_case : List[str]=32 , _snake_case : Optional[int]=2 , _snake_case : Tuple=0.1 ) -> int: '''simple docstring''' a__ = self.normalize(__lowerCamelCase , 'observations' ) a__ = obs[None].repeat(__lowerCamelCase , axis=0 ) a__ = {0: self.to_torch(__lowerCamelCase )} a__ = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) a__ = randn_tensor(__lowerCamelCase , device=self.unet.device ) a__ = self.reset_xa(__lowerCamelCase , __lowerCamelCase , self.action_dim ) a__ = self.to_torch(__lowerCamelCase ) # run the diffusion process a__ = self.run_diffusion(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # sort output trajectories by value a__ = y.argsort(0 , descending=__lowerCamelCase ).squeeze() a__ = x[sorted_idx] a__ = sorted_values[:, :, : self.action_dim] a__ = actions.detach().cpu().numpy() a__ = self.de_normalize(__lowerCamelCase , key='actions' ) # select the action with the highest value if y is not None: a__ = 0 else: # if we didn't run value guiding, select a random action a__ = np.random.randint(0 , __lowerCamelCase ) a__ = denorm_actions[selected_index, 0] return denorm_actions
232
# 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 class UpperCamelCase__ ( __lowerCamelCase ): a__ : List[str] = 'philschmid/bart-large-cnn-samsum' a__ : List[Any] = ( 'This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, ' 'and returns a summary of the text.' ) a__ : int = 'summarizer' a__ : int = AutoTokenizer a__ : Any = AutoModelForSeqaSeqLM a__ : Optional[int] = ['text'] a__ : Optional[int] = ['text'] def __lowercase( self : int, __lowerCamelCase : List[str] ) -> List[Any]: return self.pre_processor(__lowerCamelCase, return_tensors='''pt''', truncation=__lowerCamelCase ) def __lowercase( self : int, __lowerCamelCase : Union[str, Any] ) -> Union[str, Any]: return self.model.generate(**__lowerCamelCase )[0] def __lowercase( self : Optional[Any], __lowerCamelCase : Optional[int] ) -> Any: return self.pre_processor.decode(__lowerCamelCase, skip_special_tokens=__lowerCamelCase, clean_up_tokenization_spaces=__lowerCamelCase )
344
0
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed __lowerCAmelCase : Tuple = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'''{bindir}/../../examples/pytorch/translation'''): from run_translation import main # noqa set_seed(42) __lowerCAmelCase : Union[str, Any] = "sshleifer/student_marian_en_ro_6_1" __lowerCAmelCase : str = "sshleifer/tiny-mbart" @require_torch class UpperCAmelCase_ ( _lowerCamelCase ): '''simple docstring''' def _lowercase ( self : List[Any] , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : Any=True , UpperCamelCase__ : str=True , UpperCamelCase__ : Union[str, Any]=True , UpperCamelCase__ : Optional[int]=True , ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.run_trainer( eval_steps=1 , max_len=12 , model_name=A__ , num_train_epochs=1 , distributed=A__ , extra_args_str=A__ , predict_with_generate=A__ , do_train=A__ , do_eval=A__ , do_predict=A__ , ) __magic_name__ = TrainerState.load_from_json(os.path.join(A__ , """trainer_state.json""" ) ).log_history if not do_eval: return __magic_name__ = [log for log in logs if """eval_loss""" in log.keys()] __magic_name__ = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __magic_name__ = eval_metrics[-1] assert isinstance(last_step_stats["""eval_bleu"""] , A__ ) assert not math.isnan(float(last_step_stats["""eval_loss"""] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def _lowercase ( self : str ) -> Optional[int]: """simple docstring""" self.run_seqaseq_quick() @require_torch_multi_gpu def _lowercase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" self.run_seqaseq_quick(distributed=A__ ) @require_torch_multi_gpu def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" self.run_seqaseq_quick(distributed=A__ ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _lowercase ( self : Union[str, Any] ) -> Any: """simple docstring""" self.run_seqaseq_quick(distributed=A__ , extra_args_str="""--sharded_ddp simple""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _lowercase ( self : int ) -> Tuple: """simple docstring""" self.run_seqaseq_quick(distributed=A__ , extra_args_str="""--sharded_ddp simple --fp16""" ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _lowercase ( self : int ) -> str: """simple docstring""" self.run_seqaseq_quick(distributed=A__ , extra_args_str="""--sharded_ddp zero_dp_2""" , predict_with_generate=A__ ) @unittest.skip("""Requires an update of the env running those tests""" ) @require_torch_multi_gpu @require_fairscale def _lowercase ( self : Any ) -> List[str]: """simple docstring""" self.run_seqaseq_quick( distributed=A__ , extra_args_str="""--sharded_ddp zero_dp_2 --fp16""" , predict_with_generate=A__ ) @require_apex @require_torch_gpu def _lowercase ( self : Dict ) -> Optional[Any]: """simple docstring""" self.run_seqaseq_quick(distributed=A__ , extra_args_str="""--fp16 --fp16_backend=apex""" ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=A__ , extra_args_str="""--fp16 --fp16_backend=apex""" ) @parameterized.expand(["""base""", """low""", """high""", """mixed"""] ) @require_torch_multi_gpu def _lowercase ( self : List[str] , UpperCamelCase__ : int ) -> List[Any]: """simple docstring""" __magic_name__ = { # test with the default log_level - should be info and thus log info once """base""": {"""extra_args_str""": """""", """n_matches""": 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes """low""": {"""extra_args_str""": """--log_level debug --log_level_replica debug""", """n_matches""": 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica """high""": {"""extra_args_str""": """--log_level error --log_level_replica debug""", """n_matches""": 1}, # test with high log_level and log_level_replica - should be quiet on all processes """mixed""": {"""extra_args_str""": """--log_level error --log_level_replica error""", """n_matches""": 0}, } __magic_name__ = experiments[experiment_id] __magic_name__ = {"""distributed""": True, """predict_with_generate""": False, """do_eval""": False, """do_predict""": False} __magic_name__ = """Running training""" with CaptureStderr() as cl: self.run_seqaseq_quick(**A__ , extra_args_str=data["""extra_args_str"""] ) __magic_name__ = len(re.findall(A__ , cl.err ) ) self.assertEqual(A__ , data["""n_matches"""] ) @slow def _lowercase ( self : Tuple ) -> Any: """simple docstring""" __magic_name__ = self.run_trainer( eval_steps=2 , max_len=128 , model_name=A__ , learning_rate=3E-4 , num_train_epochs=10 , distributed=A__ , ) # Check metrics __magic_name__ = TrainerState.load_from_json(os.path.join(A__ , """trainer_state.json""" ) ).log_history __magic_name__ = [log for log in logs if """eval_loss""" in log.keys()] __magic_name__ = eval_metrics[0] __magic_name__ = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats["""eval_bleu"""] , A__ ) # test if do_predict saves generations and metrics __magic_name__ = os.listdir(A__ ) __magic_name__ = {os.path.basename(A__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def _lowercase ( self : Tuple ) -> Dict: """simple docstring""" from transformers.training_args import OptimizerNames def train_and_return_metrics(UpperCamelCase__ : str ) -> Tuple[int, float]: __magic_name__ = """--skip_memory_metrics 0""" __magic_name__ = self.run_trainer( max_len=128 , model_name=A__ , learning_rate=3E-4 , num_train_epochs=1 , optim=A__ , distributed=A__ , extra_args_str=A__ , do_eval=A__ , do_predict=A__ , n_gpus_to_use=1 , ) # Check metrics __magic_name__ = TrainerState.load_from_json(Path(A__ , """trainer_state.json""" ) ).log_history __magic_name__ = int(logs[0]["""train_mem_gpu_peaked_delta"""] / 2**20 ) __magic_name__ = int(logs[0]["""train_mem_gpu_alloc_delta"""] / 2**20 ) __magic_name__ = logs[0]["""train_loss"""] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __magic_name__ , __magic_name__ , __magic_name__ = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __magic_name__ , __magic_name__ , __magic_name__ = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __magic_name__ = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __magic_name__ = gpu_peak_mem_orig + gpu_alloc_mem_orig __magic_name__ = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __magic_name__ = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __magic_name__ = 120 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( A__ , A__ , """should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got""" F''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' F''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( A__ , A__ , """should use ~150MB less total gpu memory with BNB, compared to without it for this model but got""" F''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' F''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( A__ , A__ , F'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def _lowercase ( self : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict = 3E-3 , UpperCamelCase__ : Optional[int] = "adafactor" , UpperCamelCase__ : str = False , UpperCamelCase__ : str = None , UpperCamelCase__ : List[Any] = 0 , UpperCamelCase__ : List[Any] = True , UpperCamelCase__ : Optional[Any] = True , UpperCamelCase__ : Dict = True , UpperCamelCase__ : Union[str, Any] = True , UpperCamelCase__ : Optional[Any] = None , ) -> Dict: """simple docstring""" __magic_name__ = self.test_file_dir / """../fixtures/tests_samples/wmt_en_ro""" __magic_name__ = self.get_auto_remove_tmp_dir() __magic_name__ = F'''\n --model_name_or_path {model_name}\n --train_file {data_dir}/train.json\n --validation_file {data_dir}/val.json\n --test_file {data_dir}/test.json\n --output_dir {output_dir}\n --overwrite_output_dir\n --max_train_samples 8\n --max_source_length {max_len}\n --max_target_length {max_len}\n --do_train\n --num_train_epochs {str(A__ )}\n --per_device_train_batch_size 4\n --learning_rate {learning_rate}\n --warmup_steps 8\n --logging_steps 0\n --logging_strategy no\n --save_steps {str(A__ )}\n --group_by_length\n --label_smoothing_factor 0.1\n --target_lang ro_RO\n --source_lang en_XX\n '''.split() __magic_name__ = F'''\n --do_eval\n --per_device_eval_batch_size 4\n --max_eval_samples 8\n --val_max_target_length {max_len}\n --evaluation_strategy steps\n --eval_steps {str(A__ )}\n '''.split() __magic_name__ = """ --do_predict """.split() __magic_name__ = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += F'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __magic_name__ = get_gpu_count() __magic_name__ = get_torch_dist_unique_port() __magic_name__ = F'''\n -m torch.distributed.run\n --nproc_per_node={n_gpus_to_use}\n --master_port={master_port}\n {self.examples_dir_str}/pytorch/translation/run_translation.py\n '''.split() __magic_name__ = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A__ , env=self.get_env() ) else: __magic_name__ = ["""run_translation.py"""] + args with patch.object(A__ , """argv""" , A__ ): main() return output_dir
700
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available 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 ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]: """simple docstring""" __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def _lowercase ( self : Any ) -> Any: """simple docstring""" __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Tuple ) -> Any: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , ) def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple: """simple docstring""" __magic_name__ = NystromformerModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str: """simple docstring""" __magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) 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 _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.num_choices __magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : int ) -> List[Any]: """simple docstring""" __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) a__ = ( { """feature-extraction""": NystromformerModel, """fill-mask""": NystromformerForMaskedLM, """question-answering""": NystromformerForQuestionAnswering, """text-classification""": NystromformerForSequenceClassification, """token-classification""": NystromformerForTokenClassification, """zero-shot""": NystromformerForSequenceClassification, } if is_torch_available() else {} ) a__ = False a__ = False def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = NystromformerModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def _lowercase ( self : Tuple ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __magic_name__ = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def _lowercase ( self : str ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def _lowercase ( self : str ) -> Tuple: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase__ )[0] __magic_name__ = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , UpperCamelCase__ ) __magic_name__ = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) ) @slow def _lowercase ( self : int ) -> str: """simple docstring""" __magic_name__ = """the [MASK] of Belgium is Brussels""" __magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) __magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" ) with torch.no_grad(): __magic_name__ = model(encoding.input_ids ).logits __magic_name__ = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
76
0
'''simple docstring''' UpperCamelCase_ = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def lowercase__( __UpperCamelCase: dict ,__UpperCamelCase: Dict ,__UpperCamelCase: List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : int = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE : Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE : List[Any] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE : Optional[Any] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE : int = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE : Tuple = list(__UpperCamelCase ) new_path.append(__UpperCamelCase ) queue.append(__UpperCamelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(__UpperCamelCase ) # in case there's no path between the 2 nodes return [] def lowercase__( __UpperCamelCase: dict ,__UpperCamelCase: Dict ,__UpperCamelCase: List[str] ): """simple docstring""" if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE : str = [start] SCREAMING_SNAKE_CASE : List[Any] = set(__UpperCamelCase ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE : int = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE : Optional[Any] = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE : Optional[Any] = ( dist[node] if dist[target] == -1 else min(dist[target] ,dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(__UpperCamelCase ) queue.append(__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
28
'''simple docstring''' # Algorithm for the pigeonhole sorting def UpperCamelCase__ ( _lowercase : Any ) -> List[Any]: __UpperCAmelCase: List[Any] = min(_lowercase ) # min() finds the minimum value __UpperCAmelCase: List[str] = max(_lowercase ) # max() finds the maximum value __UpperCAmelCase: Dict = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size __UpperCAmelCase: str = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(_lowercase , _lowercase ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. __UpperCAmelCase: List[str] = 0 for count in range(_lowercase ): while holes[count] > 0: holes[count] -= 1 __UpperCAmelCase: Optional[int] = count + min_val i += 1 def UpperCamelCase__ ( ) -> Optional[int]: __UpperCAmelCase: Union[str, Any] = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(_lowercase ) print("""Sorted order is:""" , """ """.join(_lowercase ) ) if __name__ == "__main__": main()
523
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
702
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def __lowerCAmelCase ( __lowerCamelCase : str = "laptop" ) -> DataFrame: __lowerCAmelCase =f"""https://www.amazon.in/laptop/s?k={product}""" __lowerCAmelCase ={ """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } __lowerCAmelCase =BeautifulSoup(requests.get(__lowerCamelCase , headers=__lowerCamelCase ).text ) # Initialize a Pandas dataframe with the column titles __lowerCAmelCase =DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""" , attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""} , ) , soup.find_all("""div""" , attrs={"""class""": """a-row a-size-base a-color-base"""} ) , ): try: __lowerCAmelCase =item.ha.text __lowerCAmelCase ="""https://www.amazon.in/""" + item.ha.a["""href"""] __lowerCAmelCase =item.find("""span""" , attrs={"""class""": """a-offscreen"""} ).text try: __lowerCAmelCase =item.find("""span""" , attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: __lowerCAmelCase ="""Not available""" try: __lowerCAmelCase =( """₹""" + item.find( """span""" , attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: __lowerCAmelCase ="""""" try: __lowerCAmelCase =float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""" , """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) ) * 100 ) except ValueError: __lowerCAmelCase =float("""nan""" ) except AttributeError: pass __lowerCAmelCase =[ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __lowerCAmelCase =""" """ __lowerCAmelCase =""" """ data_frame.index += 1 return data_frame if __name__ == "__main__": lowercase_ = '''headphones''' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
456
0
import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, 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 _SCREAMING_SNAKE_CASE : @staticmethod def __snake_case( *A_ , **A_ ): pass @is_pipeline_test @require_vision @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): __SCREAMING_SNAKE_CASE = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __snake_case( self , A_ , A_ , A_ ): _UpperCAmelCase : List[Any] = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) _UpperCAmelCase : Tuple = [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] return object_detector, examples def __snake_case( self , A_ , A_ ): _UpperCAmelCase : Union[str, Any] = object_detector(examples[0] , threshold=0.0 ) _UpperCAmelCase : Dict = len(A_ ) self.assertGreater(A_ , 0 ) self.assertEqual( A_ , [ { """score""": ANY(A_ ), """label""": ANY(A_ ), """box""": {"""xmin""": ANY(A_ ), """ymin""": ANY(A_ ), """xmax""": ANY(A_ ), """ymax""": ANY(A_ )}, } for i in range(A_ ) ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __snake_case( self ): pass @require_torch def __snake_case( self ): _UpperCAmelCase : str = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) _UpperCAmelCase : Optional[Any] = object_detector( """./tests/fixtures/tests_samples/COCO/000000039769.png""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 2_04, """ymin""": 1_67, """xmax""": 2_32, """ymax""": 1_90}}, {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 2_04, """ymin""": 1_67, """xmax""": 2_32, """ymax""": 1_90}}, {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 2_04, """ymin""": 1_67, """xmax""": 2_32, """ymax""": 1_90}}, {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 5_71, """ymin""": 83, """xmax""": 5_98, """ymax""": 1_03}}, {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 5_71, """ymin""": 83, """xmax""": 5_98, """ymax""": 1_03}}, {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 5_71, """ymin""": 83, """xmax""": 5_98, """ymax""": 1_03}}, {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 4_94, """ymin""": 1_05, """xmax""": 5_21, """ymax""": 1_27}}, {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 2_74, """xmax""": 93, """ymax""": 2_97}}, {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 4_94, """ymin""": 1_05, """xmax""": 5_21, """ymax""": 1_27}}, ] , ) _UpperCAmelCase : List[str] = object_detector( [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ [ {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 2_04, """ymin""": 1_67, """xmax""": 2_32, """ymax""": 1_90}}, {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 2_04, """ymin""": 1_67, """xmax""": 2_32, """ymax""": 1_90}}, {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 2_04, """ymin""": 1_67, """xmax""": 2_32, """ymax""": 1_90}}, {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 5_71, """ymin""": 83, """xmax""": 5_98, """ymax""": 1_03}}, {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 5_71, """ymin""": 83, """xmax""": 5_98, """ymax""": 1_03}}, {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 5_71, """ymin""": 83, """xmax""": 5_98, """ymax""": 1_03}}, {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 4_94, """ymin""": 1_05, """xmax""": 5_21, """ymax""": 1_27}}, {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 2_74, """xmax""": 93, """ymax""": 2_97}}, {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 4_94, """ymin""": 1_05, """xmax""": 5_21, """ymax""": 1_27}}, ] ] , ) @require_torch @slow def __snake_case( self ): _UpperCAmelCase : List[Any] = pipeline("""zero-shot-object-detection""" ) _UpperCAmelCase : Union[str, Any] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 3_24, """ymin""": 20, """xmax""": 6_40, """ymax""": 3_73}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 1_77, """ymax""": 1_15}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 3_15, """ymax""": 4_72}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 3_35, """ymin""": 74, """xmax""": 3_71, """ymax""": 1_87}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 6_42, """ymax""": 4_76}}, ] , ) _UpperCAmelCase : str = object_detector( [ { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, ] , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 3_24, """ymin""": 20, """xmax""": 6_40, """ymax""": 3_73}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 1_77, """ymax""": 1_15}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 3_15, """ymax""": 4_72}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 3_35, """ymin""": 74, """xmax""": 3_71, """ymax""": 1_87}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 6_42, """ymax""": 4_76}}, ], [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 3_24, """ymin""": 20, """xmax""": 6_40, """ymax""": 3_73}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 1_77, """ymax""": 1_15}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 3_15, """ymax""": 4_72}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 3_35, """ymin""": 74, """xmax""": 3_71, """ymax""": 1_87}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 6_42, """ymax""": 4_76}}, ], ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __snake_case( self ): pass @require_torch @slow def __snake_case( self ): _UpperCAmelCase : Tuple = 0.2 _UpperCAmelCase : Union[str, Any] = pipeline("""zero-shot-object-detection""" ) _UpperCAmelCase : Optional[int] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=A_ , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 3_24, """ymin""": 20, """xmax""": 6_40, """ymax""": 3_73}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 1_77, """ymax""": 1_15}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 3_15, """ymax""": 4_72}}, ] , ) @require_torch @slow def __snake_case( self ): _UpperCAmelCase : Dict = 2 _UpperCAmelCase : Union[str, Any] = pipeline("""zero-shot-object-detection""" ) _UpperCAmelCase : Any = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , top_k=A_ , ) self.assertEqual( nested_simplify(A_ , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 3_24, """ymin""": 20, """xmax""": 6_40, """ymax""": 3_73}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 1_77, """ymax""": 1_15}}, ] , )
643
# 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__ ( snake_case__ : Dict ): _UpperCAmelCase : str = [False] * len(snake_case__ ) _UpperCAmelCase : str = [-1] * len(snake_case__ ) def dfs(snake_case__ : Dict , snake_case__ : Optional[Any] ): _UpperCAmelCase : str = True _UpperCAmelCase : Optional[Any] = c for u in graph[v]: if not visited[u]: dfs(snake_case__ , 1 - c ) for i in range(len(snake_case__ ) ): if not visited[i]: dfs(snake_case__ , 0 ) for i in range(len(snake_case__ ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph SCREAMING_SNAKE_CASE__ : Optional[Any] = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
643
1
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ : int = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class lowerCamelCase_ ( snake_case_ , unittest.TestCase ): _lowerCAmelCase : Optional[int] = XLMRobertaTokenizer _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast _lowerCAmelCase : List[str] = True _lowerCAmelCase : Union[str, Any] = True def __lowercase ( self : int ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : str = XLMRobertaTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = '''<pad>''' SCREAMING_SNAKE_CASE : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) , lowerCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) , lowerCAmelCase__ ) def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(lowerCAmelCase__ ) , 10_02 ) def __lowercase ( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = XLMRobertaTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase__ , [ 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 : Dict = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) SCREAMING_SNAKE_CASE : Any = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def __lowercase ( self : Tuple ): """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return SCREAMING_SNAKE_CASE : Tuple = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-xlm-roberta''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): SCREAMING_SNAKE_CASE : int = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Dict = self.tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_r.save_pretrained(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Dict = tokenizer_p.save_pretrained(lowerCAmelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE : Optional[Any] = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(lowerCAmelCase__ , lowerCAmelCase__ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE : Dict = tokenizer_r.from_pretrained(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = tokenizer_p.from_pretrained(lowerCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowerCAmelCase__ ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.save_pretrained(lowerCAmelCase__ , legacy_format=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_p.save_pretrained(lowerCAmelCase__ ) # Checks it save with the same files self.assertSequenceEqual(lowerCAmelCase__ , lowerCAmelCase__ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.from_pretrained(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = tokenizer_p.from_pretrained(lowerCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) shutil.rmtree(lowerCAmelCase__ ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Dict = tokenizer_r.save_pretrained(lowerCAmelCase__ , legacy_format=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_p.save_pretrained(lowerCAmelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE : Any = tokenizer_r.from_pretrained(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Any = tokenizer_p.from_pretrained(lowerCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) shutil.rmtree(lowerCAmelCase__ ) @cached_property def __lowercase ( self : Tuple ): """simple docstring""" return XLMRobertaTokenizer.from_pretrained('''xlm-roberta-base''' ) def __lowercase ( self : Optional[int] ): """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCAmelCase__ , f.name ) SCREAMING_SNAKE_CASE : str = XLMRobertaTokenizer(f.name , keep_accents=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = pickle.dumps(lowerCAmelCase__ ) pickle.loads(lowerCAmelCase__ ) def __lowercase ( self : Dict ): """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE : int = self.get_tokenizer() SCREAMING_SNAKE_CASE : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : List[Any] = '''I was born in 92000, and this is falsé.''' SCREAMING_SNAKE_CASE : int = tokenizer.tokenize(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.tokenize(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Any = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Dict = tokenizer.encode(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.encode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) @slow def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = '''Hello World!''' SCREAMING_SNAKE_CASE : Union[str, Any] = [0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(lowerCAmelCase__ , self.big_tokenizer.encode(lowerCAmelCase__ ) ) @slow def __lowercase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : str = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) SCREAMING_SNAKE_CASE : Any = [ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(lowerCAmelCase__ , self.big_tokenizer.encode(lowerCAmelCase__ ) ) @slow def __lowercase ( self : List[str] ): """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE : Union[str, Any] = {'''input_ids''': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=lowerCAmelCase__ , model_name='''xlm-roberta-base''' , revision='''d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3''' , )
464
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCAmelCase_ : str = logging.get_logger(__name__) lowerCAmelCase_ : List[Any] = OrderedDict( [ ('align', 'EfficientNetImageProcessor'), ('beit', 'BeitImageProcessor'), ('bit', 'BitImageProcessor'), ('blip', 'BlipImageProcessor'), ('blip-2', 'BlipImageProcessor'), ('bridgetower', 'BridgeTowerImageProcessor'), ('chinese_clip', 'ChineseCLIPImageProcessor'), ('clip', 'CLIPImageProcessor'), ('clipseg', 'ViTImageProcessor'), ('conditional_detr', 'ConditionalDetrImageProcessor'), ('convnext', 'ConvNextImageProcessor'), ('convnextv2', 'ConvNextImageProcessor'), ('cvt', 'ConvNextImageProcessor'), ('data2vec-vision', 'BeitImageProcessor'), ('deformable_detr', 'DeformableDetrImageProcessor'), ('deit', 'DeiTImageProcessor'), ('deta', 'DetaImageProcessor'), ('detr', 'DetrImageProcessor'), ('dinat', 'ViTImageProcessor'), ('donut-swin', 'DonutImageProcessor'), ('dpt', 'DPTImageProcessor'), ('efficientformer', 'EfficientFormerImageProcessor'), ('efficientnet', 'EfficientNetImageProcessor'), ('flava', 'FlavaImageProcessor'), ('focalnet', 'BitImageProcessor'), ('git', 'CLIPImageProcessor'), ('glpn', 'GLPNImageProcessor'), ('groupvit', 'CLIPImageProcessor'), ('imagegpt', 'ImageGPTImageProcessor'), ('instructblip', 'BlipImageProcessor'), ('layoutlmv2', 'LayoutLMv2ImageProcessor'), ('layoutlmv3', 'LayoutLMv3ImageProcessor'), ('levit', 'LevitImageProcessor'), ('mask2former', 'Mask2FormerImageProcessor'), ('maskformer', 'MaskFormerImageProcessor'), ('mgp-str', 'ViTImageProcessor'), ('mobilenet_v1', 'MobileNetV1ImageProcessor'), ('mobilenet_v2', 'MobileNetV2ImageProcessor'), ('mobilevit', 'MobileViTImageProcessor'), ('mobilevit', 'MobileViTImageProcessor'), ('mobilevitv2', 'MobileViTImageProcessor'), ('nat', 'ViTImageProcessor'), ('oneformer', 'OneFormerImageProcessor'), ('owlvit', 'OwlViTImageProcessor'), ('perceiver', 'PerceiverImageProcessor'), ('pix2struct', 'Pix2StructImageProcessor'), ('poolformer', 'PoolFormerImageProcessor'), ('regnet', 'ConvNextImageProcessor'), ('resnet', 'ConvNextImageProcessor'), ('sam', 'SamImageProcessor'), ('segformer', 'SegformerImageProcessor'), ('swiftformer', 'ViTImageProcessor'), ('swin', 'ViTImageProcessor'), ('swin2sr', 'Swin2SRImageProcessor'), ('swinv2', 'ViTImageProcessor'), ('table-transformer', 'DetrImageProcessor'), ('timesformer', 'VideoMAEImageProcessor'), ('tvlt', 'TvltImageProcessor'), ('upernet', 'SegformerImageProcessor'), ('van', 'ConvNextImageProcessor'), ('videomae', 'VideoMAEImageProcessor'), ('vilt', 'ViltImageProcessor'), ('vit', 'ViTImageProcessor'), ('vit_hybrid', 'ViTHybridImageProcessor'), ('vit_mae', 'ViTImageProcessor'), ('vit_msn', 'ViTImageProcessor'), ('xclip', 'CLIPImageProcessor'), ('yolos', 'YolosImageProcessor'), ] ) lowerCAmelCase_ : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def UpperCAmelCase ( A : str ): for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: SCREAMING_SNAKE_CASE : Tuple = model_type_to_module_name(A ) SCREAMING_SNAKE_CASE : List[Any] = importlib.import_module(F""".{module_name}""" , '''transformers.models''' ) try: return getattr(A , A ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(A , '''__name__''' , A ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. SCREAMING_SNAKE_CASE : List[str] = importlib.import_module('''transformers''' ) if hasattr(A , A ): return getattr(A , A ) return None def UpperCAmelCase ( A : Union[str, os.PathLike] , A : Optional[Union[str, os.PathLike]] = None , A : bool = False , A : bool = False , A : Optional[Dict[str, str]] = None , A : Optional[Union[bool, str]] = None , A : Optional[str] = None , A : bool = False , **A : List[str] , ): SCREAMING_SNAKE_CASE : List[Any] = get_file_from_repo( A , A , cache_dir=A , force_download=A , resume_download=A , proxies=A , use_auth_token=A , revision=A , local_files_only=A , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(A , encoding='''utf-8''' ) as reader: return json.load(A ) class lowerCamelCase_ : def __init__( self : Tuple ): """simple docstring""" raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(lowerCAmelCase__ ) def __lowercase ( cls : int , lowerCAmelCase__ : Optional[int] , **lowerCAmelCase__ : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = kwargs.pop('''config''' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = kwargs.pop('''trust_remote_code''' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = ImageProcessingMixin.get_image_processor_dict(lowerCAmelCase__ , **lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = config_dict.get('''image_processor_type''' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): SCREAMING_SNAKE_CASE : List[Any] = config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: SCREAMING_SNAKE_CASE : Optional[Any] = config_dict.pop('''feature_extractor_type''' , lowerCAmelCase__ ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): SCREAMING_SNAKE_CASE : Union[str, Any] = config_dict['''auto_map''']['''AutoFeatureExtractor'''] SCREAMING_SNAKE_CASE : str = feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) # It could be in `config.image_processor_type`` SCREAMING_SNAKE_CASE : Any = getattr(lowerCAmelCase__ , '''image_processor_type''' , lowerCAmelCase__ ) if hasattr(lowerCAmelCase__ , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: SCREAMING_SNAKE_CASE : Tuple = config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: SCREAMING_SNAKE_CASE : List[str] = image_processor_class_from_name(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = image_processor_auto_map is not None SCREAMING_SNAKE_CASE : str = image_processor_class is not None or type(lowerCAmelCase__ ) in IMAGE_PROCESSOR_MAPPING SCREAMING_SNAKE_CASE : Union[str, Any] = resolve_trust_remote_code( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if has_remote_code and trust_remote_code: SCREAMING_SNAKE_CASE : List[Any] = get_class_from_dynamic_module( lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''code_revision''' , lowerCAmelCase__ ) if os.path.isdir(lowerCAmelCase__ ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(lowerCAmelCase__ , **lowerCAmelCase__ ) elif image_processor_class is not None: return image_processor_class.from_dict(lowerCAmelCase__ , **lowerCAmelCase__ ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(lowerCAmelCase__ ) in IMAGE_PROCESSOR_MAPPING: SCREAMING_SNAKE_CASE : List[str] = IMAGE_PROCESSOR_MAPPING[type(lowerCAmelCase__ )] return image_processor_class.from_dict(lowerCAmelCase__ , **lowerCAmelCase__ ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int] ): """simple docstring""" IMAGE_PROCESSOR_MAPPING.register(lowerCAmelCase__ , lowerCAmelCase__ )
464
1
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def _UpperCAmelCase ( a__): '''simple docstring''' if "cls_token" in name: a_ : int = name.replace("""cls_token""" , """vit.embeddings.cls_token""") if "mask_token" in name: a_ : List[str] = name.replace("""mask_token""" , """decoder.mask_token""") if "decoder_pos_embed" in name: a_ : Optional[int] = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""") if "pos_embed" in name and "decoder" not in name: a_ : Union[str, Any] = name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""") if "patch_embed.proj" in name: a_ : Union[str, Any] = name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""") if "patch_embed.norm" in name: a_ : str = name.replace("""patch_embed.norm""" , """vit.embeddings.norm""") if "decoder_blocks" in name: a_ : Optional[int] = name.replace("""decoder_blocks""" , """decoder.decoder_layers""") if "blocks" in name: a_ : Dict = name.replace("""blocks""" , """vit.encoder.layer""") if "attn.proj" in name: a_ : Optional[Any] = name.replace("""attn.proj""" , """attention.output.dense""") if "attn" in name: a_ : Any = name.replace("""attn""" , """attention.self""") if "norm1" in name: a_ : int = name.replace("""norm1""" , """layernorm_before""") if "norm2" in name: a_ : List[Any] = name.replace("""norm2""" , """layernorm_after""") if "mlp.fc1" in name: a_ : List[Any] = name.replace("""mlp.fc1""" , """intermediate.dense""") if "mlp.fc2" in name: a_ : Optional[int] = name.replace("""mlp.fc2""" , """output.dense""") if "decoder_embed" in name: a_ : List[Any] = name.replace("""decoder_embed""" , """decoder.decoder_embed""") if "decoder_norm" in name: a_ : Dict = name.replace("""decoder_norm""" , """decoder.decoder_norm""") if "decoder_pred" in name: a_ : str = name.replace("""decoder_pred""" , """decoder.decoder_pred""") if "norm.weight" in name and "decoder" not in name: a_ : Optional[int] = name.replace("""norm.weight""" , """vit.layernorm.weight""") if "norm.bias" in name and "decoder" not in name: a_ : str = name.replace("""norm.bias""" , """vit.layernorm.bias""") return name def _UpperCAmelCase ( a__ , a__): '''simple docstring''' for key in orig_state_dict.copy().keys(): a_ : Optional[Any] = orig_state_dict.pop(a__) if "qkv" in key: a_ : List[Any] = key.split(""".""") a_ : str = int(key_split[1]) if "decoder_blocks" in key: a_ : Optional[int] = config.decoder_hidden_size a_ : Dict = """decoder.decoder_layers.""" if "weight" in key: a_ : Dict = val[:dim, :] a_ : List[Any] = val[dim : dim * 2, :] a_ : Optional[Any] = val[-dim:, :] elif "bias" in key: a_ : Optional[int] = val[:dim] a_ : Optional[int] = val[dim : dim * 2] a_ : int = val[-dim:] else: a_ : Tuple = config.hidden_size a_ : List[Any] = """vit.encoder.layer.""" if "weight" in key: a_ : Tuple = val[:dim, :] a_ : Any = val[dim : dim * 2, :] a_ : List[str] = val[-dim:, :] elif "bias" in key: a_ : int = val[:dim] a_ : str = val[dim : dim * 2] a_ : int = val[-dim:] else: a_ : int = val return orig_state_dict def _UpperCAmelCase ( a__ , a__): '''simple docstring''' a_ : List[Any] = ViTMAEConfig() if "large" in checkpoint_url: a_ : Tuple = 1_0_2_4 a_ : Optional[Any] = 4_0_9_6 a_ : List[str] = 2_4 a_ : str = 1_6 elif "huge" in checkpoint_url: a_ : int = 1_4 a_ : int = 1_2_8_0 a_ : Optional[Any] = 5_1_2_0 a_ : Optional[int] = 3_2 a_ : Any = 1_6 a_ : Tuple = ViTMAEForPreTraining(a__) a_ : Optional[Any] = torch.hub.load_state_dict_from_url(a__ , map_location="""cpu""")["""model"""] a_ : Optional[Any] = ViTMAEImageProcessor(size=config.image_size) a_ : List[str] = convert_state_dict(a__ , a__) model.load_state_dict(a__) model.eval() a_ : Optional[int] = """https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" a_ : str = Image.open(requests.get(a__ , stream=a__).raw) a_ : int = ViTMAEImageProcessor(size=config.image_size) a_ : Optional[Any] = image_processor(images=a__ , return_tensors="""pt""") # forward pass torch.manual_seed(2) a_ : Any = model(**a__) a_ : Union[str, Any] = outputs.logits if "large" in checkpoint_url: a_ : Optional[Any] = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]]) elif "huge" in checkpoint_url: a_ : Tuple = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]]) else: a_ : Dict = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]]) # verify logits assert torch.allclose(logits[0, :3, :3] , a__ , atol=1e-4) print(f'''Saving model 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 __name__ == "__main__": __snake_case : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", 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.""" ) __snake_case : List[Any] = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
540
def _UpperCAmelCase ( a__ , a__): '''simple docstring''' return x if y == 0 else greatest_common_divisor(a__ , x % y) def _UpperCAmelCase ( a__ , a__): '''simple docstring''' return (x * y) // greatest_common_divisor(a__ , a__) def _UpperCAmelCase ( a__ = 2_0): '''simple docstring''' a_ : Any = 1 for i in range(1 , n + 1): a_ : Tuple = lcm(a__ , a__) return g if __name__ == "__main__": print(F"""{solution() = }""")
540
1
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase = 50 ) -> int: lowerCamelCase_ = [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() = }''')
384
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class UpperCAmelCase : '''simple docstring''' @staticmethod def UpperCamelCase( *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' pass def _UpperCamelCase ( __UpperCamelCase ) -> str: lowerCamelCase_ = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _UpperCamelCase ( __UpperCamelCase ) -> Dict: lowerCamelCase_ = np.array(__UpperCamelCase ) lowerCamelCase_ = npimg.shape return {"hash": hashimage(__UpperCamelCase ), "shape": shape} @is_pipeline_test @require_vision @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) SCREAMING_SNAKE_CASE_ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = MaskGenerationPipeline(model=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCamelCase( self ) -> int: '''simple docstring''' pass @slow @require_torch def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) lowerCamelCase_ = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing lowerCamelCase_ = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_444}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.021}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_167}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_132}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_053}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_967}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.993}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_909}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_879}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_834}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_716}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_612}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_599}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_552}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_532}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_516}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_499}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_483}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_464}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.943}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.943}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_408}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_335}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_326}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_262}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_999}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_986}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_984}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_873}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_871} ] , ) # fmt: on @require_torch @slow def UpperCamelCase( self ) -> Any: '''simple docstring''' lowerCamelCase_ = 'facebook/sam-vit-huge' lowerCamelCase_ = pipeline('mask-generation' , model=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing lowerCamelCase_ = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_444}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_210}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_167}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_132}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_053}, ] , )
384
1
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask a : int = logging.getLogger(__name__) class __UpperCamelCase ( a__ ): def __init__( self , lowerCAmelCase__=-1 ) -> Union[str, Any]: # in NER datasets, the last column is usually reserved for NER label a : Optional[Any] = label_idx def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[InputExample]: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a : Optional[Any] = mode.value a : Any = os.path.join(lowerCAmelCase__ , f"""{mode}.txt""" ) a : Union[str, Any] = 1 a : str = [] with open(lowerCAmelCase__ , encoding="utf-8" ) as f: a : Optional[Any] = [] a : str = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"""{mode}-{guid_index}""" , words=lowerCAmelCase__ , labels=lowerCAmelCase__ ) ) guid_index += 1 a : Union[str, Any] = [] a : Union[str, Any] = [] else: a : List[str] = line.split(" " ) words.append(splits[0] ) if len(lowerCAmelCase__ ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f"""{mode}-{guid_index}""" , words=lowerCAmelCase__ , labels=lowerCAmelCase__ ) ) return examples def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: a : Any = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(lowerCAmelCase__ ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: a : int = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(lowerCAmelCase__ ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __a ( self , lowerCAmelCase__ ) -> List[str]: if path: with open(lowerCAmelCase__ , "r" ) as f: a : Any = f.read().splitlines() if "O" not in labels: a : Optional[Any] = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __UpperCamelCase ( a__ ): def __init__( self ) -> Optional[int]: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __a ( self , lowerCAmelCase__ ) -> List[str]: if path: with open(lowerCAmelCase__ , "r" ) as f: a : List[Any] = f.read().splitlines() if "O" not in labels: a : List[Any] = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __UpperCamelCase ( a__ ): def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[InputExample]: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a : Optional[Any] = mode.value a : Any = os.path.join(lowerCAmelCase__ , f"""{mode}.txt""" ) a : Optional[int] = 1 a : str = [] with open(lowerCAmelCase__ , encoding="utf-8" ) as f: for sentence in parse_incr(lowerCAmelCase__ ): a : List[str] = [] a : Optional[int] = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) if words: examples.append(InputExample(guid=f"""{mode}-{guid_index}""" , words=lowerCAmelCase__ , labels=lowerCAmelCase__ ) ) guid_index += 1 return examples def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: a : int = 0 for sentence in parse_incr(lowerCAmelCase__ ): a : Any = preds_list[example_id] a : Any = "" for token in sentence: out += f"""{token['form']} ({token['upos']}|{s_p.pop(0 )}) """ out += "\n" writer.write(lowerCAmelCase__ ) example_id += 1 def __a ( self , lowerCAmelCase__ ) -> List[str]: if path: with open(lowerCAmelCase__ , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
633
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a : int = logging.get_logger(__name__) class __UpperCamelCase ( a__ ): lowerCamelCase : Optional[int] =["""pixel_values"""] def __init__( self , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = PIL.Image.BICUBIC , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = 1 / 255 , lowerCAmelCase__ = True , lowerCAmelCase__ = True , lowerCAmelCase__ = None , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> None: super().__init__(**lowerCAmelCase__ ) a : Optional[int] = size if size is not None else {"height": 256, "width": 256} a : Tuple = get_size_dict(lowerCAmelCase__ ) a : Any = crop_size if crop_size is not None else {"height": 224, "width": 224} a : Dict = get_size_dict(lowerCAmelCase__ , param_name="crop_size" ) a : Tuple = do_resize a : int = size a : List[str] = resample a : List[Any] = do_center_crop a : List[Any] = crop_size a : Union[str, Any] = do_rescale a : List[Any] = rescale_factor a : Union[str, Any] = do_normalize a : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = PIL.Image.BICUBIC , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> np.ndarray: a : Optional[int] = get_size_dict(lowerCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""" ) return resize( lowerCAmelCase__ , size=(size["height"], size["width"]) , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> np.ndarray: a : List[str] = get_size_dict(lowerCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(lowerCAmelCase__ , size=(size["height"], size["width"]) , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> Union[str, Any]: return rescale(lowerCAmelCase__ , scale=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> np.ndarray: return normalize(lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__=None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = ChannelDimension.FIRST , **lowerCAmelCase__ , ) -> PIL.Image.Image: a : List[Any] = do_resize if do_resize is not None else self.do_resize a : str = resample if resample is not None else self.resample a : Dict = do_center_crop if do_center_crop is not None else self.do_center_crop a : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale a : str = rescale_factor if rescale_factor is not None else self.rescale_factor a : Dict = do_normalize if do_normalize is not None else self.do_normalize a : List[str] = image_mean if image_mean is not None else self.image_mean a : Union[str, Any] = image_std if image_std is not None else self.image_std a : str = size if size is not None else self.size a : Any = get_size_dict(lowerCAmelCase__ ) a : Dict = crop_size if crop_size is not None else self.crop_size a : List[str] = get_size_dict(lowerCAmelCase__ , param_name="crop_size" ) a : str = make_list_of_images(lowerCAmelCase__ ) if not valid_images(lowerCAmelCase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. a : Optional[Any] = [to_numpy_array(lowerCAmelCase__ ) for image in images] if do_resize: a : Optional[int] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ ) for image in images] if do_center_crop: a : Dict = [self.center_crop(image=lowerCAmelCase__ , size=lowerCAmelCase__ ) for image in images] if do_rescale: a : Any = [self.rescale(image=lowerCAmelCase__ , scale=lowerCAmelCase__ ) for image in images] if do_normalize: a : Optional[Any] = [self.normalize(image=lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ ) for image in images] a : Optional[Any] = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ ) for image in images] a : Tuple = {"pixel_values": images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ )
633
1
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class _lowercase : def __init__( self , UpperCamelCase_ , UpperCamelCase_=sys.maxsize ): __magic_name__ = '''bilinear''' __magic_name__ = max_size __magic_name__ = short_edge_length def __call__( self , UpperCamelCase_ ): __magic_name__ = [] for img in imgs: __magic_name__ , __magic_name__ = img.shape[:2] # later: provide list and randomly choose index for resize __magic_name__ = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img __magic_name__ = size * 1.0 / min(UpperCamelCase_ , UpperCamelCase_ ) if h < w: __magic_name__ , __magic_name__ = size, scale * w else: __magic_name__ , __magic_name__ = scale * h, size if max(UpperCamelCase_ , UpperCamelCase_ ) > self.max_size: __magic_name__ = self.max_size * 1.0 / max(UpperCamelCase_ , UpperCamelCase_ ) __magic_name__ = newh * scale __magic_name__ = neww * scale __magic_name__ = int(neww + 0.5 ) __magic_name__ = int(newh + 0.5 ) if img.dtype == np.uinta: __magic_name__ = Image.fromarray(UpperCamelCase_ ) __magic_name__ = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) __magic_name__ = np.asarray(UpperCamelCase_ ) else: __magic_name__ = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw __magic_name__ = nn.functional.interpolate( UpperCamelCase_ , (newh, neww) , mode=self.interp_method , align_corners=UpperCamelCase_ ).squeeze(0 ) img_augs.append(UpperCamelCase_ ) return img_augs class _lowercase : def __init__( self , UpperCamelCase_ ): __magic_name__ = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) __magic_name__ = cfg.INPUT.FORMAT __magic_name__ = cfg.SIZE_DIVISIBILITY __magic_name__ = cfg.PAD_VALUE __magic_name__ = cfg.INPUT.MAX_SIZE_TEST __magic_name__ = cfg.MODEL.DEVICE __magic_name__ = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) __magic_name__ = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) __magic_name__ = lambda UpperCamelCase_ : (x - self.pixel_mean) / self.pixel_std def lowerCAmelCase__ ( self , UpperCamelCase_ ): __magic_name__ = tuple(max(UpperCamelCase_ ) for s in zip(*[img.shape for img in images] ) ) __magic_name__ = [im.shape[-2:] for im in images] __magic_name__ = [ nn.functional.pad( UpperCamelCase_ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(UpperCamelCase_ , UpperCamelCase_ ) ] return torch.stack(UpperCamelCase_ ), torch.tensor(UpperCamelCase_ ) def __call__( self , UpperCamelCase_ , UpperCamelCase_=False ): with torch.no_grad(): if not isinstance(UpperCamelCase_ , UpperCamelCase_ ): __magic_name__ = [images] if single_image: assert len(UpperCamelCase_ ) == 1 for i in range(len(UpperCamelCase_ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(UpperCamelCase_ , images.pop(UpperCamelCase_ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( UpperCamelCase_ , torch.as_tensor(img_tensorize(images.pop(UpperCamelCase_ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge __magic_name__ = torch.tensor([im.shape[:2] for im in images] ) __magic_name__ = self.aug(UpperCamelCase_ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic __magic_name__ = [self.normalizer(UpperCamelCase_ ) for x in images] # now pad them to do the following operations __magic_name__ , __magic_name__ = self.pad(UpperCamelCase_ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad __magic_name__ = torch.true_divide(UpperCamelCase_ , UpperCamelCase_ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def lowercase ( __UpperCamelCase , __UpperCamelCase ) -> List[str]: boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def lowercase ( __UpperCamelCase , __UpperCamelCase ) -> int: assert torch.isfinite(__UpperCamelCase ).all(), "Box tensor contains infinite or NaN!" __magic_name__ , __magic_name__ = box_size tensor[:, 0].clamp_(min=0 , max=__UpperCamelCase ) tensor[:, 1].clamp_(min=0 , max=__UpperCamelCase ) tensor[:, 2].clamp_(min=0 , max=__UpperCamelCase ) tensor[:, 3].clamp_(min=0 , max=__UpperCamelCase )
708
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __lowerCamelCase = { "vocab_file": { "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt", "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt", "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt", "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt", "bert-base-multilingual-uncased": ( "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt" ), "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt", "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt", "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt", "bert-large-uncased-whole-word-masking": ( "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt" ), "bert-large-cased-whole-word-masking": ( "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt" ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt" ), "bert-large-cased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt" ), "bert-base-cased-finetuned-mrpc": ( "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt" ), "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt", "bert-base-german-dbmdz-uncased": ( "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt" ), "TurkuNLP/bert-base-finnish-cased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt" ), "TurkuNLP/bert-base-finnish-uncased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt" ), "wietsedv/bert-base-dutch-cased": ( "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json", "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json", "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json", "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json", "bert-base-multilingual-uncased": ( "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json" ), "bert-base-multilingual-cased": ( "https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json" ), "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json", "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json", "bert-large-uncased-whole-word-masking": ( "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json" ), "bert-large-cased-whole-word-masking": ( "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json" ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json" ), "bert-large-cased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json" ), "bert-base-cased-finetuned-mrpc": ( "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json" ), "bert-base-german-dbmdz-cased": ( "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json" ), "bert-base-german-dbmdz-uncased": ( "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json" ), "TurkuNLP/bert-base-finnish-cased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json" ), "TurkuNLP/bert-base-finnish-uncased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json" ), "wietsedv/bert-base-dutch-cased": ( "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json" ), }, } __lowerCamelCase = { "bert-base-uncased": 5_12, "bert-large-uncased": 5_12, "bert-base-cased": 5_12, "bert-large-cased": 5_12, "bert-base-multilingual-uncased": 5_12, "bert-base-multilingual-cased": 5_12, "bert-base-chinese": 5_12, "bert-base-german-cased": 5_12, "bert-large-uncased-whole-word-masking": 5_12, "bert-large-cased-whole-word-masking": 5_12, "bert-large-uncased-whole-word-masking-finetuned-squad": 5_12, "bert-large-cased-whole-word-masking-finetuned-squad": 5_12, "bert-base-cased-finetuned-mrpc": 5_12, "bert-base-german-dbmdz-cased": 5_12, "bert-base-german-dbmdz-uncased": 5_12, "TurkuNLP/bert-base-finnish-cased-v1": 5_12, "TurkuNLP/bert-base-finnish-uncased-v1": 5_12, "wietsedv/bert-base-dutch-cased": 5_12, } __lowerCamelCase = { "bert-base-uncased": {"do_lower_case": True}, "bert-large-uncased": {"do_lower_case": True}, "bert-base-cased": {"do_lower_case": False}, "bert-large-cased": {"do_lower_case": False}, "bert-base-multilingual-uncased": {"do_lower_case": True}, "bert-base-multilingual-cased": {"do_lower_case": False}, "bert-base-chinese": {"do_lower_case": False}, "bert-base-german-cased": {"do_lower_case": False}, "bert-large-uncased-whole-word-masking": {"do_lower_case": True}, "bert-large-cased-whole-word-masking": {"do_lower_case": False}, "bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True}, "bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False}, "bert-base-cased-finetuned-mrpc": {"do_lower_case": False}, "bert-base-german-dbmdz-cased": {"do_lower_case": False}, "bert-base-german-dbmdz-uncased": {"do_lower_case": True}, "TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False}, "TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True}, "wietsedv/bert-base-dutch-cased": {"do_lower_case": False}, } class _lowercase ( __UpperCAmelCase ): _lowerCamelCase = VOCAB_FILES_NAMES _lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase = PRETRAINED_INIT_CONFIGURATION _lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase = BertTokenizer def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_="[UNK]" , UpperCamelCase_="[SEP]" , UpperCamelCase_="[PAD]" , UpperCamelCase_="[CLS]" , UpperCamelCase_="[MASK]" , UpperCamelCase_=True , UpperCamelCase_=None , **UpperCamelCase_ , ): super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) __magic_name__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCamelCase_ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCamelCase_ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCamelCase_ ) != tokenize_chinese_chars ): __magic_name__ = getattr(UpperCamelCase_ , normalizer_state.pop('''type''' ) ) __magic_name__ = do_lower_case __magic_name__ = strip_accents __magic_name__ = tokenize_chinese_chars __magic_name__ = normalizer_class(**UpperCamelCase_ ) __magic_name__ = do_lower_case def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_=None ): __magic_name__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): __magic_name__ = [self.sep_token_id] __magic_name__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): __magic_name__ = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
190
0
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _UpperCamelCase (_lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Any] )-> Optional[Any]: '''simple docstring''' __snake_case = [] for part_id in partition_order: __snake_case = df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(_lowerCamelCase ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Any: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(1_00 ).repartition(1 ) __snake_case = Spark(_lowerCamelCase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Tuple: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(10 ).repartition(2 ) __snake_case = [1, 0] __snake_case = _generate_iterable_examples(_lowerCamelCase , _lowerCamelCase ) # Reverse the partitions. __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , _lowerCamelCase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): __snake_case , __snake_case = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> int: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(10 ).repartition(1 ) __snake_case = SparkExamplesIterable(_lowerCamelCase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Union[str, Any]: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('''numpy.random.Generator''' ) as generator_mock: __snake_case = lambda _lowerCamelCase : x.reverse() __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , [2, 1, 0] ) __snake_case = SparkExamplesIterable(_lowerCamelCase ).shuffle_data_sources(_lowerCamelCase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): __snake_case , __snake_case = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Tuple: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 __snake_case = SparkExamplesIterable(_lowerCamelCase ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , [0, 2] ) for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): __snake_case , __snake_case = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 __snake_case = SparkExamplesIterable(_lowerCamelCase ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 __snake_case = _get_expected_row_ids_and_row_dicts_for_partition_order(_lowerCamelCase , [1, 3] ) for i, (row_id, row_dict) in enumerate(_lowerCamelCase ): __snake_case , __snake_case = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _UpperCamelCase ()-> Optional[int]: '''simple docstring''' __snake_case = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() __snake_case = spark.range(1_00 ).repartition(1 ) __snake_case = Spark(_lowerCamelCase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_00
24
SCREAMING_SNAKE_CASE :List[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :Union[str, Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :int = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" assert len(str(a_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __A = year // 1_0_0 __A = (5 * (century % 4) + 2) % 7 __A = year % 1_0_0 __A = centurian % 1_2 __A = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __A = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __A = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
55
0
'''simple docstring''' import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @property def a ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a ( self ): '''simple docstring''' _lowerCAmelCase : List[str] = ort.SessionOptions() _lowerCAmelCase : str = False return options def a ( self ): '''simple docstring''' _lowerCAmelCase : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) _lowerCAmelCase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) _lowerCAmelCase : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default _lowerCAmelCase : Optional[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=snake_case__ ) _lowerCAmelCase : Union[str, Any] = 'A red cat sitting on a park bench' _lowerCAmelCase : Tuple = np.random.RandomState(0 ) _lowerCAmelCase : Tuple = pipe( prompt=snake_case__ , image=snake_case__ , mask_image=snake_case__ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=snake_case__ , output_type='np' , ) _lowerCAmelCase : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
630
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins lowerCAmelCase : List[str] = ["""tests.fixtures.files""", """tests.fixtures.hub""", """tests.fixtures.fsspec"""] def lowercase (_A , _A ): """simple docstring""" for item in items: if any(marker in item.keywords for marker in ['integration', 'unit'] ): continue item.add_marker(pytest.mark.unit ) def lowercase (_A ): """simple docstring""" config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' ) @pytest.fixture(autouse=_A ) def lowercase (_A , _A ): """simple docstring""" _lowerCAmelCase : str = tmp_path_factory.getbasetemp() / 'cache' _lowerCAmelCase : Dict = test_hf_cache_home / 'datasets' _lowerCAmelCase : List[Any] = test_hf_cache_home / 'metrics' _lowerCAmelCase : List[Any] = test_hf_cache_home / 'modules' monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(_A ) ) monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(_A ) ) monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(_A ) ) _lowerCAmelCase : Dict = test_hf_datasets_cache / 'downloads' monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(_A ) ) _lowerCAmelCase : Union[str, Any] = test_hf_datasets_cache / 'downloads' / 'extracted' monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_A ) ) @pytest.fixture(autouse=_A , scope='session' ) def lowercase (): """simple docstring""" datasets.disable_progress_bar() @pytest.fixture(autouse=_A ) def lowercase (_A ): """simple docstring""" monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , _A ) @pytest.fixture def lowercase (_A ): """simple docstring""" monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , _A )
630
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase ={ "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase =[ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
617
"""simple docstring""" import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"): UpperCAmelCase =True from torch.cuda.amp import autocast UpperCAmelCase =logging.getLogger(__name__) @dataclass class lowerCamelCase__ : '''simple docstring''' _lowerCamelCase = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether to log verbose messages or not.'''} , ) _lowerCamelCase = field( default=2.0 , metadata={'''help''': '''Maximum temperature for gumbel softmax.'''} ) _lowerCamelCase = field( default=0.5 , metadata={'''help''': '''Minimum temperature for gumbel softmax.'''} ) _lowerCamelCase = field( default=0.9_9_9_9_9_5 , metadata={'''help''': '''Decay of gumbel temperature during training.'''} ) def _A ( _a : ModelArguments , _a : TrainingArguments ): """simple docstring""" logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) A = logging.WARNING if model_args.verbose_logging: A = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): A = logging.INFO logger.setLevel(_a ) @dataclass class lowerCamelCase__ : '''simple docstring''' _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) _lowerCamelCase = field( default='''train''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) _lowerCamelCase = field( default='''validation''' , metadata={ '''help''': ( '''The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'''' ) } , ) _lowerCamelCase = field( default='''file''' , metadata={'''help''': '''Column in the dataset that contains speech file path. Defaults to \'file\''''} , ) _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} ) _lowerCamelCase = field( default=1 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) _lowerCamelCase = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) _lowerCamelCase = field( default=2_0.0 , metadata={'''help''': '''Filter audio files that are longer than `max_duration_in_seconds` seconds'''} ) @dataclass class lowerCamelCase__ : '''simple docstring''' _lowerCamelCase = 42 _lowerCamelCase = 42 _lowerCamelCase = "longest" _lowerCamelCase = None _lowerCamelCase = None def __call__( self ,lowerCamelCase_ ) -> Dict[str, torch.Tensor]: # reformat list to dict and set to pytorch format A = self.feature_extractor.pad( lowerCamelCase_ ,max_length=self.max_length ,padding=self.padding ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors="""pt""" ,) A = self.model._get_feat_extract_output_lengths(batch["""input_values"""].shape[-1] ) A = batch["""input_values"""].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula A = self.model._get_feat_extract_output_lengths(batch["""attention_mask"""].sum(-1 ) ).to( torch.long ) A = torch.zeros( (batch_size, mask_indices_seq_length) ,dtype=torch.long ,device=batch["""input_values"""].device ) # these two operations makes sure that all values # before the output lengths indices are attended to A = 1 A = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices A = _compute_mask_indices( (batch_size, mask_indices_seq_length) ,self.model.config.mask_time_prob ,self.model.config.mask_time_length ,attention_mask=lowerCamelCase_ ,min_masks=2 ,) return batch class lowerCamelCase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self ,*lowerCamelCase_ ,lowerCamelCase_=1 ,lowerCamelCase_=0 ,lowerCamelCase_=1.0 ,**lowerCamelCase_ ) -> Union[str, Any]: super().__init__(*lowerCamelCase_ ,**lowerCamelCase_ ) A = 0 A = max_gumbel_temp A = min_gumbel_temp A = gumbel_temp_decay def UpperCamelCase__ ( self ,lowerCamelCase_ ,lowerCamelCase_ ) -> torch.Tensor: model.train() A = self._prepare_inputs(lowerCamelCase_ ) if self.use_amp: with autocast(): A = self.compute_loss(lowerCamelCase_ ,lowerCamelCase_ ) else: A = self.compute_loss(lowerCamelCase_ ,lowerCamelCase_ ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": A = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": A = loss.sum() / (inputs["""mask_time_indices"""]).sum() else: raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' ) if self.args.gradient_accumulation_steps > 1: A = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(lowerCamelCase_ ).backward() elif self.use_apex: with amp.scale_loss(lowerCamelCase_ ,self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(lowerCamelCase_ ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step ,self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step ,self.min_gumbel_temp ) ) return loss.detach() def _A ( ): """simple docstring""" A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) A , A , A = parser.parse_args_into_dataclasses() configure_logger(_a , _a ) # Downloading and loading a dataset from the hub. A = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" A = DatasetDict() A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'{data_args.train_split_name}[:{data_args.validation_split_percentage}%]' , cache_dir=model_args.cache_dir , ) A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'{data_args.train_split_name}[{data_args.validation_split_percentage}%:]' , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" A = DatasetDict() A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split="""validation""" , cache_dir=model_args.cache_dir , ) A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'{data_args.train_split_name}' , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported A = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=_a ) def prepare_dataset(_a : Dict ): # check that all files have the correct sampling rate A , A = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays A = datasets.map( _a , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets["""train"""].column_names ) # filter audio files that are too long A = vectorized_datasets.filter( lambda _a : len(data["""speech"""] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(_a : Optional[Any] ): return feature_extractor(batch["""speech"""] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` A = vectorized_datasets.map( _a , batched=_a , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets["""train"""].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 A = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( """PreTraining is only supported for ``config.do_stable_layer_norm=True`` and""" """ ``config.feat_extract_norm='layer'""" ) A = WavaVecaForPreTraining(_a ) A = DataCollatorForWavaVecaPretraining(model=_a , feature_extractor=_a ) A = WavaVecaPreTrainer( model=_a , data_collator=_a , args=_a , train_dataset=vectorized_datasets["""train"""] , eval_dataset=vectorized_datasets["""validation"""] , tokenizer=_a , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
617
1
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class a : """simple docstring""" def __init__( self : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : List[str]=13 , lowerCamelCase : Tuple=7 , lowerCamelCase : int=True , lowerCamelCase : Any=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[Any]=99 , lowerCamelCase : Optional[int]=24 , lowerCamelCase : Union[str, Any]=2 , lowerCamelCase : Any=6 , lowerCamelCase : Optional[int]=37 , lowerCamelCase : Union[str, Any]="gelu" , lowerCamelCase : Dict=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=512 , lowerCamelCase : List[str]=16 , lowerCamelCase : Optional[int]=2 , lowerCamelCase : Union[str, Any]=0.02 , lowerCamelCase : Any=3 , lowerCamelCase : Optional[Any]=None , lowerCamelCase : Optional[Any]=1000 , ) -> Dict: __snake_case : Optional[Any] = parent __snake_case : Tuple = batch_size __snake_case : int = seq_length __snake_case : List[str] = is_training __snake_case : Tuple = use_input_mask __snake_case : Union[str, Any] = use_token_type_ids __snake_case : List[Any] = use_labels __snake_case : Union[str, Any] = vocab_size __snake_case : Tuple = hidden_size __snake_case : Tuple = num_hidden_layers __snake_case : Optional[int] = num_attention_heads __snake_case : Tuple = intermediate_size __snake_case : Tuple = hidden_act __snake_case : Optional[Any] = hidden_dropout_prob __snake_case : Optional[Any] = attention_probs_dropout_prob __snake_case : Any = max_position_embeddings __snake_case : Optional[int] = type_vocab_size __snake_case : List[Any] = type_sequence_label_size __snake_case : int = initializer_range __snake_case : str = num_labels __snake_case : List[Any] = scope __snake_case : str = range_bbox def __snake_case ( self : Optional[Any] ) -> Optional[int]: __snake_case : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __snake_case : Optional[Any] = bbox[i, j, 3] __snake_case : str = bbox[i, j, 1] __snake_case : int = t if bbox[i, j, 2] < bbox[i, j, 0]: __snake_case : Dict = bbox[i, j, 2] __snake_case : Union[str, Any] = bbox[i, j, 0] __snake_case : Optional[Any] = t __snake_case : Union[str, Any] = None if self.use_input_mask: __snake_case : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __snake_case : Union[str, Any] = None if self.use_token_type_ids: __snake_case : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case : List[Any] = None __snake_case : Optional[Any] = None if self.use_labels: __snake_case : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : List[str] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __snake_case ( self : Union[str, Any] ) -> str: return LiltConfig( 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 , ) def __snake_case ( self : List[str] , lowerCamelCase : Dict , lowerCamelCase : Dict , lowerCamelCase : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict , lowerCamelCase : List[str] , lowerCamelCase : Dict , ) -> List[str]: __snake_case : Dict = LiltModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Optional[Any] = model(lowerCamelCase , bbox=lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase ) __snake_case : int = model(lowerCamelCase , bbox=lowerCamelCase , token_type_ids=lowerCamelCase ) __snake_case : Dict = model(lowerCamelCase , bbox=lowerCamelCase ) 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 __snake_case ( self : Union[str, Any] , lowerCamelCase : str , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict , lowerCamelCase : Tuple , lowerCamelCase : Dict , lowerCamelCase : Dict , lowerCamelCase : Dict , ) -> str: __snake_case : List[Any] = self.num_labels __snake_case : List[str] = LiltForTokenClassification(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Optional[Any] = model( lowerCamelCase , bbox=lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __snake_case ( self : str , lowerCamelCase : Dict , lowerCamelCase : List[Any] , lowerCamelCase : Dict , lowerCamelCase : Dict , lowerCamelCase : Tuple , lowerCamelCase : List[str] , lowerCamelCase : Any , ) -> Any: __snake_case : Optional[int] = LiltForQuestionAnswering(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Optional[int] = model( lowerCamelCase , bbox=lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , start_positions=lowerCamelCase , end_positions=lowerCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __snake_case ( self : str ) -> Union[str, Any]: __snake_case : List[str] = self.prepare_config_and_inputs() ( __snake_case ) : Optional[Any] = config_and_inputs __snake_case : Optional[Any] = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Tuple = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCAmelCase : List[str] = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : int = False __UpperCAmelCase : str = False def __snake_case ( self : List[str] , lowerCamelCase : Optional[int] , lowerCamelCase : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict , lowerCamelCase : Optional[int] ) -> List[Any]: return True def __snake_case ( self : str ) -> List[str]: __snake_case : str = LiltModelTester(self ) __snake_case : int = ConfigTester(self , config_class=lowerCamelCase , hidden_size=37 ) def __snake_case ( self : List[Any] ) -> Any: self.config_tester.run_common_tests() def __snake_case ( self : str ) -> Tuple: __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def __snake_case ( self : List[str] ) -> str: __snake_case : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __snake_case : Dict = type self.model_tester.create_and_check_model(*lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> Optional[Any]: __snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCamelCase ) def __snake_case ( self : Any ) -> int: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCamelCase ) @slow def __snake_case ( self : Dict ) -> int: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[Any] = LiltModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) @require_torch @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> List[str]: __snake_case : Optional[int] = LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base" ).to(lowerCamelCase ) __snake_case : List[str] = torch.tensor([[1, 2]] , device=lowerCamelCase ) __snake_case : List[str] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : List[str] = model(input_ids=lowerCamelCase , bbox=lowerCamelCase ) __snake_case : List[str] = torch.Size([1, 2, 768] ) __snake_case : str = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowerCamelCase , ) self.assertTrue(outputs.last_hidden_state.shape , lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowerCamelCase , atol=1E-3 ) )
704
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset _snake_case : Any = "bert-base-cased" _snake_case : List[Any] = "google/pegasus-xsum" _snake_case : Dict = [" Sam ate lunch today.", "Sams lunch ingredients."] _snake_case : Dict = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"] _snake_case : List[str] = "patrickvonplaten/t5-tiny-random" _snake_case : Optional[Any] = "sshleifer/bart-tiny-random" _snake_case : Optional[Any] = "sshleifer/tiny-mbart" _snake_case : Tuple = "sshleifer/tiny-marian-en-de" def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): __snake_case : Union[str, Any] = "\n".join(__lowerCamelCase ) Path(__lowerCamelCase ).open("w" ).writelines(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): for split in ["train", "val", "test"]: _dump_articles(os.path.join(__lowerCamelCase , F'{split}.source' ) , __lowerCamelCase ) _dump_articles(os.path.join(__lowerCamelCase , F'{split}.target' ) , __lowerCamelCase ) return tmp_dir class a (_lowerCAmelCase ): """simple docstring""" @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def __snake_case ( self : List[Any] , lowerCamelCase : int ) -> Union[str, Any]: __snake_case : Optional[Any] = AutoTokenizer.from_pretrained(lowerCamelCase ) __snake_case : List[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) __snake_case : Optional[int] = max(len(tokenizer.encode(lowerCamelCase ) ) for a in ARTICLES ) __snake_case : Optional[int] = max(len(tokenizer.encode(lowerCamelCase ) ) for a in SUMMARIES ) __snake_case : str = 4 __snake_case : Optional[int] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated __snake_case , __snake_case : Optional[int] = "ro_RO", "de_DE" # ignored for all but mbart, but never causes error. __snake_case : List[str] = SeqaSeqDataset( lowerCamelCase , data_dir=lowerCamelCase , type_path="train" , max_source_length=lowerCamelCase , max_target_length=lowerCamelCase , src_lang=lowerCamelCase , tgt_lang=lowerCamelCase , ) __snake_case : str = DataLoader(lowerCamelCase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(lowerCamelCase , lowerCamelCase ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place __snake_case : int = shift_tokens_right(batch["labels"] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] ) -> Optional[Any]: __snake_case : Any = AutoTokenizer.from_pretrained(lowerCamelCase ) __snake_case : List[str] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) __snake_case : Union[str, Any] = max(len(tokenizer.encode(lowerCamelCase ) ) for a in ARTICLES ) __snake_case : Tuple = max(len(tokenizer.encode(lowerCamelCase ) ) for a in SUMMARIES ) __snake_case : List[str] = 4 __snake_case : List[str] = LegacySeqaSeqDataset( lowerCamelCase , data_dir=lowerCamelCase , type_path="train" , max_source_length=20 , max_target_length=lowerCamelCase , ) __snake_case : int = DataLoader(lowerCamelCase , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def __snake_case ( self : List[str] ) -> int: __snake_case : str = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25" ) __snake_case : int = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) __snake_case : str = tmp_dir.joinpath("train.source" ).open().readlines() __snake_case : Any = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(lowerCamelCase , lowerCamelCase , 128 , lowerCamelCase ) __snake_case : str = {x.name for x in tmp_dir.iterdir()} __snake_case : Optional[int] = {x.name for x in save_dir.iterdir()} __snake_case : Optional[int] = save_dir.joinpath("train.source" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(lowerCamelCase ) < len(lowerCamelCase ) assert len(lowerCamelCase ) == 1 assert len(packed_examples[0] ) == sum(len(lowerCamelCase ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="This test requires fairseq" ) def __snake_case ( self : Tuple ) -> str: if not FAIRSEQ_AVAILABLE: return __snake_case , __snake_case , __snake_case : Optional[Any] = self._get_dataset(max_len=64 ) __snake_case : Optional[int] = 64 __snake_case : List[Any] = ds.make_dynamic_sampler(lowerCamelCase , required_batch_size_multiple=lowerCamelCase ) __snake_case : str = [len(lowerCamelCase ) for x in batch_sampler] assert len(set(lowerCamelCase ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(lowerCamelCase ) == len(lowerCamelCase ) # no dropped or added examples __snake_case : Optional[Any] = DataLoader(lowerCamelCase , batch_sampler=lowerCamelCase , collate_fn=ds.collate_fn , num_workers=2 ) __snake_case : Union[str, Any] = [] __snake_case : str = [] for batch in data_loader: __snake_case : str = batch["input_ids"].shape __snake_case : Dict = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple __snake_case : str = np.product(batch["input_ids"].shape ) num_src_per_batch.append(lowerCamelCase ) if num_src_tokens > (max_tokens * 1.1): failures.append(lowerCamelCase ) assert num_src_per_batch[0] == max(lowerCamelCase ) if failures: raise AssertionError(F'too many tokens in {len(lowerCamelCase )} batches' ) def __snake_case ( self : int ) -> Any: __snake_case , __snake_case , __snake_case : Union[str, Any] = self._get_dataset(max_len=512 ) __snake_case : Union[str, Any] = 2 __snake_case : List[str] = ds.make_sortish_sampler(lowerCamelCase , shuffle=lowerCamelCase ) __snake_case : Dict = DataLoader(lowerCamelCase , batch_size=lowerCamelCase , collate_fn=ds.collate_fn , num_workers=2 ) __snake_case : List[Any] = DataLoader(lowerCamelCase , batch_size=lowerCamelCase , collate_fn=ds.collate_fn , num_workers=2 , sampler=lowerCamelCase ) __snake_case : List[Any] = tokenizer.pad_token_id def count_pad_tokens(lowerCamelCase : List[Any] , lowerCamelCase : Optional[int]="input_ids" ): return [batch[k].eq(lowerCamelCase ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(lowerCamelCase , k="labels" ) ) < sum(count_pad_tokens(lowerCamelCase , k="labels" ) ) assert sum(count_pad_tokens(lowerCamelCase ) ) < sum(count_pad_tokens(lowerCamelCase ) ) assert len(lowerCamelCase ) == len(lowerCamelCase ) def __snake_case ( self : Any , lowerCamelCase : List[Any]=1000 , lowerCamelCase : Union[str, Any]=128 ) -> Any: if os.getenv("USE_REAL_DATA" , lowerCamelCase ): __snake_case : int = "examples/seq2seq/wmt_en_ro" __snake_case : Union[str, Any] = max_len * 2 * 64 if not Path(lowerCamelCase ).joinpath("train.len" ).exists(): save_len_file(lowerCamelCase , lowerCamelCase ) else: __snake_case : List[str] = "examples/seq2seq/test_data/wmt_en_ro" __snake_case : List[Any] = max_len * 4 save_len_file(lowerCamelCase , lowerCamelCase ) __snake_case : Dict = AutoTokenizer.from_pretrained(lowerCamelCase ) __snake_case : int = SeqaSeqDataset( lowerCamelCase , data_dir=lowerCamelCase , type_path="train" , max_source_length=lowerCamelCase , max_target_length=lowerCamelCase , n_obs=lowerCamelCase , ) return ds, max_tokens, tokenizer def __snake_case ( self : Tuple ) -> Dict: __snake_case , __snake_case , __snake_case : Any = self._get_dataset() __snake_case : Optional[Any] = set(DistributedSortishSampler(lowerCamelCase , 256 , num_replicas=2 , rank=0 , add_extra_examples=lowerCamelCase ) ) __snake_case : int = set(DistributedSortishSampler(lowerCamelCase , 256 , num_replicas=2 , rank=1 , add_extra_examples=lowerCamelCase ) ) assert idsa.intersection(lowerCamelCase ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def __snake_case ( self : List[str] , lowerCamelCase : Union[str, Any] ) -> str: __snake_case : Tuple = AutoTokenizer.from_pretrained(lowerCamelCase , use_fast=lowerCamelCase ) if tok_name == MBART_TINY: __snake_case : Dict = SeqaSeqDataset( lowerCamelCase , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , src_lang="EN" , tgt_lang="FR" , ) __snake_case : Any = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: __snake_case : Union[str, Any] = SeqaSeqDataset( lowerCamelCase , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , ) __snake_case : Optional[int] = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(lowerCamelCase ) == 1 if tok_name == BART_TINY else len(lowerCamelCase ) == 0
203
0
'''simple docstring''' from __future__ import annotations import typing from collections.abc import Iterable import numpy as np a__ : int = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 a__ : str = typing.Union[np.floataa, int, float] # noqa: UP007 def __lowerCamelCase ( UpperCAmelCase_ , UpperCAmelCase_ ) ->VectorOut: return np.sqrt(np.sum((np.asarray(UpperCAmelCase_ ) - np.asarray(UpperCAmelCase_ )) ** 2 ) ) def __lowerCamelCase ( UpperCAmelCase_ , UpperCAmelCase_ ) ->VectorOut: return sum((va - va) ** 2 for va, va in zip(UpperCAmelCase_ , UpperCAmelCase_ ) ) ** (1 / 2) if __name__ == "__main__": def __lowerCamelCase ( ) ->None: from timeit import timeit print('Without Numpy' ) print( timeit( 'euclidean_distance_no_np([1, 2, 3], [4, 5, 6])' , number=1_00_00 , globals=globals() , ) ) print('With Numpy' ) print( timeit( 'euclidean_distance([1, 2, 3], [4, 5, 6])' , number=1_00_00 , globals=globals() , ) ) benchmark()
368
'''simple docstring''' import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor a__ : int = logging.get_logger(__name__) class __snake_case ( __magic_name__ ): def __init__( self , *UpperCamelCase_ , **UpperCamelCase_ ) -> None: warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , UpperCamelCase_ , ) super().__init__(*UpperCamelCase_ , **UpperCamelCase_ )
368
1
import numpy as np class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = (0, 0) UpperCamelCase__ = None UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 def __eq__(self , SCREAMING_SNAKE_CASE_ ): return self.position == cell.position def UpperCAmelCase_ (self ): print(self.position ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_=(5, 5) ): UpperCamelCase__ = np.zeros(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = world_size[0] UpperCamelCase__ = world_size[1] def UpperCAmelCase_ (self ): print(self.w ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] UpperCamelCase__ = cell.position[0] UpperCamelCase__ = cell.position[1] UpperCamelCase__ = [] for n in neughbour_cord: UpperCamelCase__ = current_x + n[0] UpperCamelCase__ = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: UpperCamelCase__ = Cell() UpperCamelCase__ = (x, y) UpperCamelCase__ = cell neighbours.append(SCREAMING_SNAKE_CASE_ ) return neighbours def __magic_name__ ( __a : Optional[Any] , __a : str , __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = [] _open.append(__a ) while _open: UpperCamelCase__ = np.argmin([n.f for n in _open] ) UpperCamelCase__ = _open[min_f] _closed.append(_open.pop(__a ) ) if current == goal: break for n in world.get_neigbours(__a ): for c in _closed: if c == n: continue UpperCamelCase__ = current.g + 1 UpperCamelCase__ , UpperCamelCase__ = n.position UpperCamelCase__ , UpperCamelCase__ = goal.position UpperCamelCase__ = (ya - ya) ** 2 + (xa - xa) ** 2 UpperCamelCase__ = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(__a ) UpperCamelCase__ = [] while current.parent is not None: path.append(current.position ) UpperCamelCase__ = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowerCamelCase_ = Gridworld() # Start position and goal lowerCamelCase_ = Cell() lowerCamelCase_ = (0, 0) lowerCamelCase_ = Cell() lowerCamelCase_ = (4, 4) print(f'path from {start.position} to {goal.position}') lowerCamelCase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowerCamelCase_ = 1 print(world.w)
86
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
1
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor snake_case__ : Optional[Any] = logging.get_logger(__name__) class _a ( UpperCAmelCase__ ): """simple docstring""" def __init__( self , *_UpperCAmelCase , **_UpperCAmelCase ) -> None: warnings.warn( 'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use LayoutLMv2ImageProcessor instead.' , _UpperCAmelCase , ) super().__init__(*_UpperCAmelCase , **_UpperCAmelCase )
23
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class SCREAMING_SNAKE_CASE ( __a ): """simple docstring""" def __init__( self : List[Any] , __lowerCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] , __lowerCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , __lowerCAmelCase : Optional[Features] = None , __lowerCAmelCase : str = None , __lowerCAmelCase : bool = False , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(features=__lowerCAmelCase , cache_dir=__lowerCAmelCase , keep_in_memory=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCAmelCase = Sql( cache_dir=__lowerCAmelCase , features=__lowerCAmelCase , sql=__lowerCAmelCase , con=__lowerCAmelCase , **__lowerCAmelCase , ) def a ( self : str ): """simple docstring""" _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = None self.builder.download_and_prepare( download_config=__lowerCAmelCase , download_mode=__lowerCAmelCase , verification_mode=__lowerCAmelCase , base_path=__lowerCAmelCase , ) # Build dataset for splits _lowerCAmelCase = self.builder.as_dataset( split='train' , verification_mode=__lowerCAmelCase , in_memory=self.keep_in_memory ) return dataset class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict , __lowerCAmelCase : Dataset , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Optional[int] = None , **__lowerCAmelCase : Tuple , ): """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(F"num_proc {num_proc} must be an integer > 0." ) _lowerCAmelCase = dataset _lowerCAmelCase = name _lowerCAmelCase = con _lowerCAmelCase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _lowerCAmelCase = num_proc _lowerCAmelCase = to_sql_kwargs def a ( self : Optional[int] ): """simple docstring""" _lowerCAmelCase = self.to_sql_kwargs.pop('sql' , __lowerCAmelCase ) _lowerCAmelCase = self.to_sql_kwargs.pop('con' , __lowerCAmelCase ) _lowerCAmelCase = self.to_sql_kwargs.pop('index' , __lowerCAmelCase ) _lowerCAmelCase = self._write(index=__lowerCAmelCase , **self.to_sql_kwargs ) return written def a ( self : Any , __lowerCAmelCase : int ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = args _lowerCAmelCase = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _lowerCAmelCase = query_table( table=self.dataset.data , key=slice(__lowerCAmelCase , offset + self.batch_size ) , indices=self.dataset._indices , ) _lowerCAmelCase = batch.to_pandas() _lowerCAmelCase = df.to_sql(self.name , self.con , index=__lowerCAmelCase , **__lowerCAmelCase ) return num_rows or len(__lowerCAmelCase ) def a ( self : Dict , __lowerCAmelCase : List[Any] , **__lowerCAmelCase : Dict ): """simple docstring""" _lowerCAmelCase = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _lowerCAmelCase , _lowerCAmelCase = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , __lowerCAmelCase , __lowerCAmelCase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += num_rows return written
309
0
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __magic_name__ ( A__ ): lowercase : Dict =(IPNDMScheduler,) lowercase : Optional[int] =(('''num_inference_steps''', 50),) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , **UpperCamelCase__ : Optional[Any] ) -> str: '''simple docstring''' UpperCAmelCase = {"num_train_timesteps": 10_00} config.update(**UpperCamelCase__ ) return config def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , UpperCamelCase__ : Optional[int]=0 , **UpperCamelCase__ : Any ) -> Tuple: '''simple docstring''' UpperCAmelCase = dict(self.forward_default_kwargs ) UpperCAmelCase = kwargs.pop("num_inference_steps" , UpperCamelCase__ ) UpperCAmelCase = self.dummy_sample UpperCAmelCase = 0.1 * sample UpperCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: UpperCAmelCase = self.get_scheduler_config(**UpperCamelCase__ ) UpperCAmelCase = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals UpperCAmelCase = dummy_past_residuals[:] if time_step is None: UpperCAmelCase = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase__ ) UpperCAmelCase = scheduler_class.from_pretrained(UpperCamelCase__ ) new_scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals UpperCAmelCase = dummy_past_residuals[:] UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample UpperCAmelCase = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample UpperCAmelCase = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Dict , UpperCamelCase__ : Any=0 , **UpperCamelCase__ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase = dict(self.forward_default_kwargs ) UpperCAmelCase = kwargs.pop("num_inference_steps" , UpperCamelCase__ ) UpperCAmelCase = self.dummy_sample UpperCAmelCase = 0.1 * sample UpperCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals (must be after setting timesteps) UpperCAmelCase = dummy_past_residuals[:] if time_step is None: UpperCAmelCase = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase__ ) UpperCAmelCase = scheduler_class.from_pretrained(UpperCamelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residual (must be after setting timesteps) UpperCAmelCase = dummy_past_residuals[:] UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample UpperCAmelCase = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample UpperCAmelCase = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE_ ( self : Dict , **UpperCamelCase__ : Any ) -> str: '''simple docstring''' UpperCAmelCase = self.scheduler_classes[0] UpperCAmelCase = self.get_scheduler_config(**UpperCamelCase__ ) UpperCAmelCase = scheduler_class(**UpperCamelCase__ ) UpperCAmelCase = 10 UpperCAmelCase = self.dummy_model() UpperCAmelCase = self.dummy_sample_deter scheduler.set_timesteps(UpperCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = model(UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample for i, t in enumerate(scheduler.timesteps ): UpperCAmelCase = model(UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample return sample def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> int: '''simple docstring''' UpperCAmelCase = dict(self.forward_default_kwargs ) UpperCAmelCase = kwargs.pop("num_inference_steps" , UpperCamelCase__ ) for scheduler_class in self.scheduler_classes: UpperCAmelCase = self.get_scheduler_config() UpperCAmelCase = scheduler_class(**UpperCamelCase__ ) UpperCAmelCase = self.dummy_sample UpperCAmelCase = 0.1 * sample if num_inference_steps is not None and hasattr(UpperCamelCase__ , "set_timesteps" ): scheduler.set_timesteps(UpperCamelCase__ ) elif num_inference_steps is not None and not hasattr(UpperCamelCase__ , "set_timesteps" ): UpperCAmelCase = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) UpperCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] UpperCAmelCase = dummy_past_residuals[:] UpperCAmelCase = scheduler.timesteps[5] UpperCAmelCase = scheduler.timesteps[6] UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample UpperCAmelCase = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' for timesteps in [1_00, 10_00]: self.check_over_configs(num_train_timesteps=UpperCamelCase__ , time_step=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Dict: '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ): self.check_over_forward(num_inference_steps=UpperCamelCase__ , time_step=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: '''simple docstring''' UpperCAmelCase = self.full_loop() UpperCAmelCase = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_mean.item() - 2_54_05_29 ) < 10
457
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCamelCase : Optional[int] = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys __lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
457
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
424
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _SCREAMING_SNAKE_CASE : Optional[Any] = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def __lowerCAmelCase ( ): _lowercase: List[Any] = _ask_options( "In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: _lowercase: Any = get_sagemaker_input() else: _lowercase: Tuple = get_cluster_input() return config def __lowerCAmelCase ( __magic_name__=None ): if subparsers is not None: _lowercase: List[Any] = subparsers.add_parser("config" , description=__magic_name__ ) else: _lowercase: List[Any] = argparse.ArgumentParser("Accelerate config command" , description=__magic_name__ ) parser.add_argument( "--config_file" , default=__magic_name__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=__magic_name__ ) return parser def __lowerCAmelCase ( __magic_name__ ): _lowercase: Union[str, Any] = get_user_input() if args.config_file is not None: _lowercase: Dict = args.config_file else: if not os.path.isdir(__magic_name__ ): os.makedirs(__magic_name__ ) _lowercase: Tuple = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(__magic_name__ ) else: config.to_yaml_file(__magic_name__ ) print(f"accelerate configuration saved at {config_file}" ) def __lowerCAmelCase ( ): _lowercase: int = config_command_parser() _lowercase: List[Any] = parser.parse_args() config_command(__magic_name__ ) if __name__ == "__main__": main()
226
0
def A__ ( lowerCamelCase , lowerCamelCase ) -> List[Any]: return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def A__ ( lowerCamelCase , lowerCamelCase=0 ) -> Optional[Any]: return sorted(lowerCamelCase , key=lambda lowerCamelCase : x[column] ) def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase=float("""inf""" ) ) -> Optional[int]: for i in range(points_counts - 1 ): for j in range(i + 1 , lowerCamelCase ): UpperCamelCase_: Any = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: UpperCamelCase_: Any = current_dis return min_dis def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase=float("""inf""" ) ) -> Tuple: for i in range(min(6 , points_counts - 1 ) , lowerCamelCase ): for j in range(max(0 , i - 6 ) , lowerCamelCase ): UpperCamelCase_: Optional[int] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: UpperCamelCase_: Dict = current_dis return min_dis def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> int: # base case if points_counts <= 3: return dis_between_closest_pair(lowerCamelCase , lowerCamelCase ) # recursion UpperCamelCase_: int = points_counts // 2 UpperCamelCase_: Optional[Any] = closest_pair_of_points_sqr( lowerCamelCase , points_sorted_on_y[:mid] , lowerCamelCase ) UpperCamelCase_: str = closest_pair_of_points_sqr( lowerCamelCase , points_sorted_on_y[mid:] , points_counts - mid ) UpperCamelCase_: Dict = min(lowerCamelCase , lowerCamelCase ) UpperCamelCase_: List[str] = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(lowerCamelCase ) UpperCamelCase_: Dict = dis_between_closest_in_strip( lowerCamelCase , len(lowerCamelCase ) , lowerCamelCase ) return min(lowerCamelCase , lowerCamelCase ) def A__ ( lowerCamelCase , lowerCamelCase ) -> List[str]: UpperCamelCase_: str = column_based_sort(lowerCamelCase , column=0 ) UpperCamelCase_: Tuple = column_based_sort(lowerCamelCase , column=1 ) return ( closest_pair_of_points_sqr( lowerCamelCase , lowerCamelCase , lowerCamelCase ) ) ** 0.5 if __name__ == "__main__": lowerCamelCase_ : int = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("""Distance:""", closest_pair_of_points(points, len(points)))
670
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) lowerCamelCase_ : Union[str, Any] = logging.getLogger() lowerCamelCase_ : List[str] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCamelCase ( _A ): '''simple docstring''' def lowerCAmelCase__ ( self : List[Any] , snake_case_ : Dict ): os.makedirs(snake_case_ , exist_ok=snake_case_ ) UpperCamelCase_: int = {"""source""": """What is love ?""", """target""": """life"""} UpperCamelCase_: Tuple = {"""train""": 12, """val""": 2, """test""": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: UpperCamelCase_: Tuple = """\n""".join([contents[field]] * n_lines[split] ) with open(os.path.join(snake_case_ , f'''{split}.{field}''' ) , """w""" ) as f: f.write(snake_case_ ) def lowerCAmelCase__ ( self : Dict , snake_case_ : int , snake_case_ : str = "pytorch" ): UpperCamelCase_: Optional[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase_: Dict = os.path.join(snake_case_ , """output""" ) UpperCamelCase_: Any = os.path.join(snake_case_ , """data""" ) self._create_dummy_data(data_dir=snake_case_ ) UpperCamelCase_: Union[str, Any] = f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append("""--fp16""" ) else: testargs.append("""--gpus=0""" ) testargs.append("""--distributed_backend=ddp_cpu""" ) testargs.append("""--num_processes=2""" ) UpperCamelCase_: Optional[Any] = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(snake_case_ , env=self.get_env() ) UpperCamelCase_: Optional[int] = os.path.join(snake_case_ , """metrics.json""" ) with open(snake_case_ ) as f: UpperCamelCase_: Any = json.load(snake_case_ ) return result @require_torch_gpu def lowerCAmelCase__ ( self : Optional[Any] ): UpperCamelCase_: List[str] = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_multi_gpu def lowerCAmelCase__ ( self : Optional[Any] ): UpperCamelCase_: Any = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_gpu @require_ray def lowerCAmelCase__ ( self : Dict ): UpperCamelCase_: List[Any] = self._run_finetune(gpus=1 , distributed_retriever="""ray""" ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_multi_gpu @require_ray def lowerCAmelCase__ ( self : Dict ): UpperCamelCase_: List[Any] = self._run_finetune(gpus=1 , distributed_retriever="""ray""" ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 )
670
1
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def lowerCamelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: '''simple docstring''' lowerCamelCase__ =hf_hub_url(repo_id=__lowerCAmelCase , path=__lowerCAmelCase , revision=__lowerCAmelCase ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(__lowerCAmelCase )}'''
530
"""simple docstring""" def lowerCamelCase_ ( __lowerCAmelCase ) -> list: '''simple docstring''' if len(__lowerCAmelCase ) <= 1: return [tuple(__lowerCAmelCase )] lowerCamelCase__ =[] def generate(__lowerCAmelCase , __lowerCAmelCase ): lowerCamelCase__ =[0] * n res.append(tuple(__lowerCAmelCase ) ) lowerCamelCase__ =0 while i < n: if c[i] < i: if i % 2 == 0: lowerCamelCase__ , lowerCamelCase__ =arr[i], arr[0] else: lowerCamelCase__ , lowerCamelCase__ =arr[i], arr[c[i]] res.append(tuple(__lowerCAmelCase ) ) c[i] += 1 lowerCamelCase__ =0 else: lowerCamelCase__ =0 i += 1 generate(len(__lowerCAmelCase ) , __lowerCAmelCase ) return res if __name__ == "__main__": a =input('Enter numbers separated by a comma:\n').strip() a =[int(item) for item in user_input.split(',')] print(heaps(arr))
530
1
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) snake_case_ = parser.parse_args() snake_case_ = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
388
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class SCREAMING_SNAKE_CASE__ : @staticmethod def a (*a__ : Optional[Any] , **a__ : Optional[Any] ): """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): A_ : Optional[Any] = MODEL_FOR_OBJECT_DETECTION_MAPPING def a (self : str , a__ : List[Any] , a__ : Optional[Any] , a__ : List[str] ): """simple docstring""" __snake_case = ObjectDetectionPipeline(model=a__ , image_processor=a__ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def a (self : List[str] , a__ : Optional[Any] , a__ : Union[str, Any] ): """simple docstring""" __snake_case = object_detector('''./tests/fixtures/tests_samples/COCO/000000039769.png''' , threshold=0.0 ) self.assertGreater(len(a__ ) , 0 ) for detected_object in outputs: self.assertEqual( a__ , { '''score''': ANY(a__ ), '''label''': ANY(a__ ), '''box''': {'''xmin''': ANY(a__ ), '''ymin''': ANY(a__ ), '''xmax''': ANY(a__ ), '''ymax''': ANY(a__ )}, } , ) import datasets __snake_case = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) __snake_case = [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] __snake_case = object_detector(a__ , threshold=0.0 ) self.assertEqual(len(a__ ) , len(a__ ) ) for outputs in batch_outputs: self.assertGreater(len(a__ ) , 0 ) for detected_object in outputs: self.assertEqual( a__ , { '''score''': ANY(a__ ), '''label''': ANY(a__ ), '''box''': {'''xmin''': ANY(a__ ), '''ymin''': ANY(a__ ), '''xmax''': ANY(a__ ), '''ymax''': ANY(a__ )}, } , ) @require_tf @unittest.skip('''Object detection not implemented in TF''' ) def a (self : Union[str, Any] ): """simple docstring""" pass @require_torch def a (self : Any ): """simple docstring""" __snake_case = '''hf-internal-testing/tiny-detr-mobilenetsv3''' __snake_case = AutoModelForObjectDetection.from_pretrained(a__ ) __snake_case = AutoFeatureExtractor.from_pretrained(a__ ) __snake_case = ObjectDetectionPipeline(model=a__ , feature_extractor=a__ ) __snake_case = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=0.0 ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''score''': 0.3_3_7_6, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, {'''score''': 0.3_3_7_6, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, ] , ) __snake_case = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {'''score''': 0.3_3_7_6, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, {'''score''': 0.3_3_7_6, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, ], [ {'''score''': 0.3_3_7_6, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, {'''score''': 0.3_3_7_6, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 159, '''ymin''': 120, '''xmax''': 480, '''ymax''': 359}}, ], ] , ) @require_torch @slow def a (self : int ): """simple docstring""" __snake_case = '''facebook/detr-resnet-50''' __snake_case = AutoModelForObjectDetection.from_pretrained(a__ ) __snake_case = AutoFeatureExtractor.from_pretrained(a__ ) __snake_case = ObjectDetectionPipeline(model=a__ , feature_extractor=a__ ) __snake_case = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''score''': 0.9_9_8_2, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9_9_6_0, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9_9_5_5, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ] , ) __snake_case = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {'''score''': 0.9_9_8_2, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9_9_6_0, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9_9_5_5, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], [ {'''score''': 0.9_9_8_2, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9_9_6_0, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9_9_5_5, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], ] , ) @require_torch @slow def a (self : List[Any] ): """simple docstring""" __snake_case = '''facebook/detr-resnet-50''' __snake_case = pipeline('''object-detection''' , model=a__ ) __snake_case = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''score''': 0.9_9_8_2, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9_9_6_0, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9_9_5_5, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ] , ) __snake_case = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ [ {'''score''': 0.9_9_8_2, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9_9_6_0, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9_9_5_5, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], [ {'''score''': 0.9_9_8_2, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 70, '''xmax''': 175, '''ymax''': 117}}, {'''score''': 0.9_9_6_0, '''label''': '''remote''', '''box''': {'''xmin''': 333, '''ymin''': 72, '''xmax''': 368, '''ymax''': 187}}, {'''score''': 0.9_9_5_5, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 639, '''ymax''': 473}}, {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ], ] , ) @require_torch @slow def a (self : str ): """simple docstring""" __snake_case = 0.9_9_8_5 __snake_case = '''facebook/detr-resnet-50''' __snake_case = pipeline('''object-detection''' , model=a__ ) __snake_case = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=a__ ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''score''': 0.9_9_8_8, '''label''': '''cat''', '''box''': {'''xmin''': 13, '''ymin''': 52, '''xmax''': 314, '''ymax''': 470}}, {'''score''': 0.9_9_8_7, '''label''': '''cat''', '''box''': {'''xmin''': 345, '''ymin''': 23, '''xmax''': 640, '''ymax''': 368}}, ] , ) @require_torch @require_pytesseract @slow def a (self : Dict ): """simple docstring""" __snake_case = '''Narsil/layoutlmv3-finetuned-funsd''' __snake_case = 0.9_9_9_3 __snake_case = pipeline('''object-detection''' , model=a__ , threshold=a__ ) __snake_case = object_detector( '''https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png''' ) self.assertEqual( nested_simplify(a__ , decimals=4 ) , [ {'''score''': 0.9_9_9_3, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 294, '''ymin''': 254, '''xmax''': 343, '''ymax''': 264}}, {'''score''': 0.9_9_9_3, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 294, '''ymin''': 254, '''xmax''': 343, '''ymax''': 264}}, ] , )
388
1
import re from ..utils import cached_file # docstyle-ignore _lowercase = ''' Human: <<task>> Assistant: ''' _lowercase = '''huggingface-tools/default-prompts''' _lowercase = {'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''} def _A (UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : Tuple="run" ) ->List[Any]: '''simple docstring''' if prompt_or_repo_id is None: lowerCamelCase__ : Optional[Any] = DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search("""\\s""" , lowerCAmelCase_ ) is not None: return prompt_or_repo_id lowerCamelCase__ : Union[str, Any] = cached_file( lowerCAmelCase_ , PROMPT_FILES[mode] , repo_type="""dataset""" , user_agent={"""agent""": agent_name} ) with open(lowerCAmelCase_ , """r""" , encoding="""utf-8""" ) as f: return f.read()
157
"""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.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): A__ : str = '''openai/whisper-base''' A__ : List[Any] = ( '''This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the ''' '''transcribed text.''' ) A__ : str = '''transcriber''' A__ : List[Any] = WhisperProcessor A__ : Optional[int] = WhisperForConditionalGeneration A__ : List[str] = ['''audio'''] A__ : Optional[int] = ['''text'''] def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : List[Any] ): """simple docstring""" return self.pre_processor(__lowerCamelCase , return_tensors='''pt''' ).input_features def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : List[str] ): """simple docstring""" return self.model.generate(inputs=__lowerCamelCase ) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : int ): """simple docstring""" return self.pre_processor.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase )[0]
103
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _snake_case = logging.get_logger(__name__) def __lowerCamelCase ( _lowercase , _lowercase ) -> int: UpperCamelCase = b.T UpperCamelCase = np.sum(np.square(_lowercase ) , axis=1 ) UpperCamelCase = np.sum(np.square(_lowercase ) , axis=0 ) UpperCamelCase = np.matmul(_lowercase , _lowercase ) UpperCamelCase = aa[:, None] - 2 * ab + ba[None, :] return d def __lowerCamelCase ( _lowercase , _lowercase ) -> Dict: UpperCamelCase = x.reshape(-1 , 3 ) UpperCamelCase = squared_euclidean_distance(_lowercase , _lowercase ) return np.argmin(_lowercase , axis=1 ) class _lowerCAmelCase ( __magic_name__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] =["pixel_values"] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Union[List[List[int]], np.ndarray]] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase = size if size is not None else {'height': 2_56, 'width': 2_56} UpperCamelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = np.array(SCREAMING_SNAKE_CASE__ ) if clusters is not None else None UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = resample UpperCamelCase = do_normalize UpperCamelCase = do_color_quantize def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ): """simple docstring""" UpperCamelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(F'Size dictionary must contain both height and width keys. Got {size.keys()}' ) return resize( SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , ): """simple docstring""" UpperCamelCase = rescale(image=SCREAMING_SNAKE_CASE__ , scale=1 / 127.5 , data_format=SCREAMING_SNAKE_CASE__ ) UpperCamelCase = image - 1 return image def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[List[List[int]], np.ndarray]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Any , ): """simple docstring""" UpperCamelCase = do_resize if do_resize is not None else self.do_resize UpperCamelCase = size if size is not None else self.size UpperCamelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = resample if resample is not None else self.resample UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase = clusters if clusters is not None else self.clusters UpperCamelCase = np.array(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. UpperCamelCase = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: UpperCamelCase = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: UpperCamelCase = [self.normalize(image=SCREAMING_SNAKE_CASE__ ) for image in images] if do_color_quantize: UpperCamelCase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase = np.array(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = color_quantize(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase = images.shape[0] UpperCamelCase = images.reshape(SCREAMING_SNAKE_CASE__ , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase = list(SCREAMING_SNAKE_CASE__ ) else: UpperCamelCase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] UpperCamelCase = {'input_ids': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
170
from typing import Dict, Optional import numpy as np import datasets _snake_case = ''' IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation, the mean IoU of the image is calculated by taking the IoU of each class and averaging them. ''' _snake_case = ''' Args: predictions (`List[ndarray]`): List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size. references (`List[ndarray]`): List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size. num_labels (`int`): Number of classes (categories). ignore_index (`int`): Index that will be ignored during evaluation. nan_to_num (`int`, *optional*): If specified, NaN values will be replaced by the number defined by the user. label_map (`dict`, *optional*): If specified, dictionary mapping old label indices to new label indices. reduce_labels (`bool`, *optional*, defaults to `False`): Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255. Returns: `Dict[str, float | ndarray]` comprising various elements: - *mean_iou* (`float`): Mean Intersection-over-Union (IoU averaged over all categories). - *mean_accuracy* (`float`): Mean accuracy (averaged over all categories). - *overall_accuracy* (`float`): Overall accuracy on all images. - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`): Per category accuracy. - *per_category_iou* (`ndarray` of shape `(num_labels,)`): Per category IoU. Examples: >>> import numpy as np >>> mean_iou = datasets.load_metric("mean_iou") >>> # suppose one has 3 different segmentation maps predicted >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]]) >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]]) >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]]) >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]]) >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]]) >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]]) >>> predicted = [predicted_1, predicted_2, predicted_3] >>> ground_truth = [actual_1, actual_2, actual_3] >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False) >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])} ''' _snake_case = '''\ @software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020, author = {{MMSegmentation Contributors}}, license = {Apache-2.0}, month = {7}, title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}}, url = {https://github.com/open-mmlab/mmsegmentation}, year = {2020} }''' def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase = None , _lowercase = False , ) -> List[str]: if label_map is not None: for old_id, new_id in label_map.items(): UpperCamelCase = new_id # turn into Numpy arrays UpperCamelCase = np.array(_lowercase ) UpperCamelCase = np.array(_lowercase ) if reduce_labels: UpperCamelCase = 255 UpperCamelCase = label - 1 UpperCamelCase = 255 UpperCamelCase = label != ignore_index UpperCamelCase = np.not_equal(_lowercase , _lowercase ) UpperCamelCase = pred_label[mask] UpperCamelCase = np.array(_lowercase )[mask] UpperCamelCase = pred_label[pred_label == label] UpperCamelCase = np.histogram(_lowercase , bins=_lowercase , range=(0, num_labels - 1) )[0] UpperCamelCase = np.histogram(_lowercase , bins=_lowercase , range=(0, num_labels - 1) )[0] UpperCamelCase = np.histogram(_lowercase , bins=_lowercase , range=(0, num_labels - 1) )[0] UpperCamelCase = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase = None , _lowercase = False , ) -> Optional[Any]: UpperCamelCase = np.zeros((num_labels,) , dtype=np.floataa ) UpperCamelCase = np.zeros((num_labels,) , dtype=np.floataa ) UpperCamelCase = np.zeros((num_labels,) , dtype=np.floataa ) UpperCamelCase = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(_lowercase , _lowercase ): UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = intersect_and_union( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , ) -> List[Any]: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = total_intersect_and_union( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) # compute metrics UpperCamelCase = {} UpperCamelCase = total_area_intersect.sum() / total_area_label.sum() UpperCamelCase = total_area_intersect / total_area_union UpperCamelCase = total_area_intersect / total_area_label UpperCamelCase = np.nanmean(_lowercase ) UpperCamelCase = np.nanmean(_lowercase ) UpperCamelCase = all_acc UpperCamelCase = iou UpperCamelCase = acc if nan_to_num is not None: UpperCamelCase = {metric: np.nan_to_num(_lowercase , nan=_lowercase ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self : List[str] ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { 'predictions': datasets.Sequence(datasets.Sequence(datasets.Value('uint16' ) ) ), 'references': datasets.Sequence(datasets.Sequence(datasets.Value('uint16' ) ) ), } ) , reference_urls=[ 'https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py' ] , ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Dict[int, int]] = None , SCREAMING_SNAKE_CASE__ : bool = False , ): """simple docstring""" UpperCamelCase = mean_iou( results=SCREAMING_SNAKE_CASE__ , gt_seg_maps=SCREAMING_SNAKE_CASE__ , num_labels=SCREAMING_SNAKE_CASE__ , ignore_index=SCREAMING_SNAKE_CASE__ , nan_to_num=SCREAMING_SNAKE_CASE__ , label_map=SCREAMING_SNAKE_CASE__ , reduce_labels=SCREAMING_SNAKE_CASE__ , ) return iou_result
170
1
"""simple docstring""" from math import sqrt def SCREAMING_SNAKE_CASE ( __UpperCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ = 0 for i in range(1 , int(sqrt(__UpperCAmelCase ) + 1 ) ): if n % i == 0 and i != sqrt(__UpperCAmelCase ): total += i + n // i elif i == sqrt(__UpperCAmelCase ): total += i return total - n def SCREAMING_SNAKE_CASE ( __UpperCAmelCase = 10_000 ) -> int: SCREAMING_SNAKE_CASE__ = sum( i for i in range(1 , __UpperCAmelCase ) if sum_of_divisors(sum_of_divisors(__UpperCAmelCase ) ) == i and sum_of_divisors(__UpperCAmelCase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
159
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _A = { 'configuration_squeezebert': [ 'SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SqueezeBertConfig', 'SqueezeBertOnnxConfig', ], 'tokenization_squeezebert': ['SqueezeBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['SqueezeBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'SqueezeBertForMaskedLM', 'SqueezeBertForMultipleChoice', 'SqueezeBertForQuestionAnswering', 'SqueezeBertForSequenceClassification', 'SqueezeBertForTokenClassification', 'SqueezeBertModel', 'SqueezeBertModule', 'SqueezeBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
159
1
import copy import re class _snake_case : _lowercase : Tuple = '''hp''' _lowercase : Optional[int] = {} _lowercase : Union[str, Any] = None @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , a) -> Union[str, Any]: SCREAMING_SNAKE_CASE = prefix SCREAMING_SNAKE_CASE = defaults cls.build_naming_info() @staticmethod def SCREAMING_SNAKE_CASE__ ( a , a) -> Union[str, Any]: if len(a) == 0: return "" SCREAMING_SNAKE_CASE = None if any(char.isdigit() for char in word): raise Exception(f'''Parameters should not contain numbers: \'{word}\' contains a number''') if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(a) + 1): SCREAMING_SNAKE_CASE = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: SCREAMING_SNAKE_CASE = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(a): SCREAMING_SNAKE_CASE = '' while integer != 0: SCREAMING_SNAKE_CASE = chr(ord('A') + integer % 10) + s integer //= 10 return s SCREAMING_SNAKE_CASE = 0 while True: SCREAMING_SNAKE_CASE = word + '#' + int_to_alphabetic(a) if sword in info["reverse_short_word"]: continue else: SCREAMING_SNAKE_CASE = sword break SCREAMING_SNAKE_CASE = short_word SCREAMING_SNAKE_CASE = word return short_word @staticmethod def SCREAMING_SNAKE_CASE__ ( a , a) -> List[Any]: SCREAMING_SNAKE_CASE = param_name.split('_') SCREAMING_SNAKE_CASE = [TrialShortNamer.shortname_for_word(a , a) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name SCREAMING_SNAKE_CASE = ['', '_'] for separator in separators: SCREAMING_SNAKE_CASE = separator.join(a) if shortname not in info["reverse_short_param"]: SCREAMING_SNAKE_CASE = shortname SCREAMING_SNAKE_CASE = param_name return shortname return param_name @staticmethod def SCREAMING_SNAKE_CASE__ ( a , a) -> int: SCREAMING_SNAKE_CASE = TrialShortNamer.shortname_for_key(a , a) SCREAMING_SNAKE_CASE = short_name SCREAMING_SNAKE_CASE = param_name @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[str]: if cls.NAMING_INFO is not None: return SCREAMING_SNAKE_CASE = { 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } SCREAMING_SNAKE_CASE = list(cls.DEFAULTS.keys()) for k in field_keys: cls.add_new_param_name(a , a) SCREAMING_SNAKE_CASE = info @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a) -> Optional[int]: cls.build_naming_info() assert cls.PREFIX is not None SCREAMING_SNAKE_CASE = [copy.copy(cls.PREFIX)] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f'''You should provide a default value for the param name {k} with value {v}''') if v == cls.DEFAULTS[k]: # The default value is not added to the name continue SCREAMING_SNAKE_CASE = cls.NAMING_INFO['short_param'][k] if isinstance(a , a): SCREAMING_SNAKE_CASE = 1 if v else 0 SCREAMING_SNAKE_CASE = '' if isinstance(a , (int, float)) else '-' SCREAMING_SNAKE_CASE = f'''{key}{sep}{v}''' name.append(a) return "_".join(a) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a) -> Optional[int]: SCREAMING_SNAKE_CASE = repr[len(cls.PREFIX) + 1 :] if repr == "": SCREAMING_SNAKE_CASE = [] else: SCREAMING_SNAKE_CASE = repr.split('_') SCREAMING_SNAKE_CASE = {} for value in values: if "-" in value: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = value.split('-') else: SCREAMING_SNAKE_CASE = re.sub('[0-9.]' , '' , a) SCREAMING_SNAKE_CASE = float(re.sub('[^0-9.]' , '' , a)) SCREAMING_SNAKE_CASE = cls.NAMING_INFO['reverse_short_param'][p_k] SCREAMING_SNAKE_CASE = p_v for k in cls.DEFAULTS: if k not in parameters: SCREAMING_SNAKE_CASE = cls.DEFAULTS[k] return parameters
444
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a_ : str = logging.get_logger(__name__) a_ : List[Any] = Dict[str, Any] a_ : Optional[int] = List[Prediction] @add_end_docstrings(A__ ) class _snake_case ( A__ ): def __init__( self , *a , **a) -> int: super().__init__(*a , **a) if self.framework == "tf": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''') requires_backends(self , 'vision') self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items())) def SCREAMING_SNAKE_CASE__ ( self , **a) -> int: SCREAMING_SNAKE_CASE = {} if "threshold" in kwargs: SCREAMING_SNAKE_CASE = kwargs['threshold'] return {}, {}, postprocess_kwargs def __call__( self , *a , **a) -> Union[Predictions, List[Prediction]]: return super().__call__(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: SCREAMING_SNAKE_CASE = load_image(a) SCREAMING_SNAKE_CASE = torch.IntTensor([[image.height, image.width]]) SCREAMING_SNAKE_CASE = self.image_processor(images=[image] , return_tensors='pt') if self.tokenizer is not None: SCREAMING_SNAKE_CASE = self.tokenizer(text=inputs['words'] , boxes=inputs['boxes'] , return_tensors='pt') SCREAMING_SNAKE_CASE = target_size return inputs def SCREAMING_SNAKE_CASE__ ( self , a) -> int: SCREAMING_SNAKE_CASE = model_inputs.pop('target_size') SCREAMING_SNAKE_CASE = self.model(**a) SCREAMING_SNAKE_CASE = outputs.__class__({'target_size': target_size, **outputs}) if self.tokenizer is not None: SCREAMING_SNAKE_CASE = model_inputs['bbox'] return model_outputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0.9) -> Dict: SCREAMING_SNAKE_CASE = model_outputs['target_size'] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = target_size[0].tolist() def unnormalize(a): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ])) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model_outputs['logits'].squeeze(0).softmax(dim=-1).max(dim=-1) SCREAMING_SNAKE_CASE = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] SCREAMING_SNAKE_CASE = [unnormalize(a) for bbox in model_outputs['bbox'].squeeze(0)] SCREAMING_SNAKE_CASE = ['score', 'label', 'box'] SCREAMING_SNAKE_CASE = [dict(zip(a , a)) for vals in zip(scores.tolist() , a , a) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel SCREAMING_SNAKE_CASE = self.image_processor.post_process_object_detection(a , a , a) SCREAMING_SNAKE_CASE = raw_annotations[0] SCREAMING_SNAKE_CASE = raw_annotation['scores'] SCREAMING_SNAKE_CASE = raw_annotation['labels'] SCREAMING_SNAKE_CASE = raw_annotation['boxes'] SCREAMING_SNAKE_CASE = scores.tolist() SCREAMING_SNAKE_CASE = [self.model.config.idalabel[label.item()] for label in labels] SCREAMING_SNAKE_CASE = [self._get_bounding_box(a) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] SCREAMING_SNAKE_CASE = ['score', 'label', 'box'] SCREAMING_SNAKE_CASE = [ dict(zip(a , a)) for vals in zip(raw_annotation['scores'] , raw_annotation['labels'] , raw_annotation['boxes']) ] return annotation def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict[str, int]: if self.framework != "pt": raise ValueError('The ObjectDetectionPipeline is only available in PyTorch.') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = box.int().tolist() SCREAMING_SNAKE_CASE = { 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, } return bbox
444
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig _lowerCamelCase : Tuple = logging.get_logger(__name__) # General docstring _lowerCamelCase : Union[str, Any] = '''ResNetConfig''' # Base docstring _lowerCamelCase : int = '''microsoft/resnet-50''' _lowerCamelCase : Optional[Any] = [1, 2_048, 7, 7] # Image classification docstring _lowerCamelCase : int = '''microsoft/resnet-50''' _lowerCamelCase : Optional[int] = '''tiger cat''' _lowerCamelCase : str = [ '''microsoft/resnet-50''', # See all resnet models at https://huggingface.co/models?filter=resnet ] class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , lowercase : int , lowercase : int , lowercase : int = 3 , lowercase : int = 1 , lowercase : str = "relu" ): '''simple docstring''' super().__init__() _snake_case = nn.Convad( lowercase , lowercase , kernel_size=lowercase , stride=lowercase , padding=kernel_size // 2 , bias=lowercase ) _snake_case = nn.BatchNormad(lowercase ) _snake_case = ACTaFN[activation] if activation is not None else nn.Identity() def A ( self : Union[str, Any] , lowercase : Tensor ): '''simple docstring''' _snake_case = self.convolution(lowercase ) _snake_case = self.normalization(lowercase ) _snake_case = self.activation(lowercase ) return hidden_state class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , lowercase : ResNetConfig ): '''simple docstring''' super().__init__() _snake_case = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) _snake_case = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) _snake_case = config.num_channels def A ( self : Tuple , lowercase : Tensor ): '''simple docstring''' _snake_case = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' ) _snake_case = self.embedder(lowercase ) _snake_case = self.pooler(lowercase ) return embedding class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Union[str, Any] , lowercase : int , lowercase : int , lowercase : int = 2 ): '''simple docstring''' super().__init__() _snake_case = nn.Convad(lowercase , lowercase , kernel_size=1 , stride=lowercase , bias=lowercase ) _snake_case = nn.BatchNormad(lowercase ) def A ( self : List[str] , lowercase : Tensor ): '''simple docstring''' _snake_case = self.convolution(lowercase ) _snake_case = self.normalization(lowercase ) return hidden_state class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , lowercase : int , lowercase : int , lowercase : int = 1 , lowercase : str = "relu" ): '''simple docstring''' super().__init__() _snake_case = in_channels != out_channels or stride != 1 _snake_case = ( ResNetShortCut(lowercase , lowercase , stride=lowercase ) if should_apply_shortcut else nn.Identity() ) _snake_case = nn.Sequential( ResNetConvLayer(lowercase , lowercase , stride=lowercase ) , ResNetConvLayer(lowercase , lowercase , activation=lowercase ) , ) _snake_case = ACTaFN[activation] def A ( self : List[str] , lowercase : List[str] ): '''simple docstring''' _snake_case = hidden_state _snake_case = self.layer(lowercase ) _snake_case = self.shortcut(lowercase ) hidden_state += residual _snake_case = self.activation(lowercase ) return hidden_state class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , lowercase : int , lowercase : int , lowercase : int = 1 , lowercase : str = "relu" , lowercase : int = 4 ): '''simple docstring''' super().__init__() _snake_case = in_channels != out_channels or stride != 1 _snake_case = out_channels // reduction _snake_case = ( ResNetShortCut(lowercase , lowercase , stride=lowercase ) if should_apply_shortcut else nn.Identity() ) _snake_case = nn.Sequential( ResNetConvLayer(lowercase , lowercase , kernel_size=1 ) , ResNetConvLayer(lowercase , lowercase , stride=lowercase ) , ResNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=lowercase ) , ) _snake_case = ACTaFN[activation] def A ( self : Dict , lowercase : Union[str, Any] ): '''simple docstring''' _snake_case = hidden_state _snake_case = self.layer(lowercase ) _snake_case = self.shortcut(lowercase ) hidden_state += residual _snake_case = self.activation(lowercase ) return hidden_state class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Dict , lowercase : ResNetConfig , lowercase : int , lowercase : int , lowercase : int = 2 , lowercase : int = 2 , ): '''simple docstring''' super().__init__() _snake_case = ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer _snake_case = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(lowercase , lowercase , stride=lowercase , activation=config.hidden_act ) , *[layer(lowercase , lowercase , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def A ( self : List[str] , lowercase : Tensor ): '''simple docstring''' _snake_case = input for layer in self.layers: _snake_case = layer(lowercase ) return hidden_state class SCREAMING_SNAKE_CASE__ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , lowercase : ResNetConfig ): '''simple docstring''' super().__init__() _snake_case = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) _snake_case = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(lowercase , config.depths[1:] ): self.stages.append(ResNetStage(lowercase , lowercase , lowercase , depth=lowercase ) ) def A ( self : str , lowercase : Tensor , lowercase : bool = False , lowercase : bool = True ): '''simple docstring''' _snake_case = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _snake_case = hidden_states + (hidden_state,) _snake_case = stage_module(lowercase ) if output_hidden_states: _snake_case = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=lowercase , hidden_states=lowercase , ) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] = ResNetConfig _UpperCAmelCase : Tuple = "resnet" _UpperCAmelCase : Optional[Any] = "pixel_values" _UpperCAmelCase : Dict = True def A ( self : List[str] , lowercase : Dict ): '''simple docstring''' if isinstance(lowercase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' ) elif isinstance(lowercase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def A ( self : Tuple , lowercase : List[Any] , lowercase : Optional[Any]=False ): '''simple docstring''' if isinstance(lowercase , lowercase ): _snake_case = value _lowerCamelCase : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' _lowerCamelCase : int = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare ResNet model outputting raw features without any specific head on top." ,UpperCAmelCase ,) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowercase : Any ): '''simple docstring''' super().__init__(lowercase ) _snake_case = config _snake_case = ResNetEmbeddings(lowercase ) _snake_case = ResNetEncoder(lowercase ) _snake_case = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=lowercase , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def A ( self : Union[str, Any] , lowercase : Tensor , lowercase : Optional[bool] = None , lowercase : Optional[bool] = None ): '''simple docstring''' _snake_case = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _snake_case = return_dict if return_dict is not None else self.config.use_return_dict _snake_case = self.embedder(lowercase ) _snake_case = self.encoder( lowercase , output_hidden_states=lowercase , return_dict=lowercase ) _snake_case = encoder_outputs[0] _snake_case = self.pooler(lowercase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=lowercase , pooler_output=lowercase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( "\n ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " ,UpperCAmelCase ,) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' def __init__( self : List[Any] , lowercase : int ): '''simple docstring''' super().__init__(lowercase ) _snake_case = config.num_labels _snake_case = ResNetModel(lowercase ) # classification head _snake_case = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def A ( self : Union[str, Any] , lowercase : Optional[torch.FloatTensor] = None , lowercase : Optional[torch.LongTensor] = None , lowercase : Optional[bool] = None , lowercase : Optional[bool] = None , ): '''simple docstring''' _snake_case = return_dict if return_dict is not None else self.config.use_return_dict _snake_case = self.resnet(lowercase , output_hidden_states=lowercase , return_dict=lowercase ) _snake_case = outputs.pooler_output if return_dict else outputs[1] _snake_case = self.classifier(lowercase ) _snake_case = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _snake_case = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _snake_case = 'single_label_classification' else: _snake_case = 'multi_label_classification' if self.config.problem_type == "regression": _snake_case = MSELoss() if self.num_labels == 1: _snake_case = loss_fct(logits.squeeze() , labels.squeeze() ) else: _snake_case = loss_fct(lowercase , lowercase ) elif self.config.problem_type == "single_label_classification": _snake_case = CrossEntropyLoss() _snake_case = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _snake_case = BCEWithLogitsLoss() _snake_case = loss_fct(lowercase , lowercase ) if not return_dict: _snake_case = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowercase , logits=lowercase , hidden_states=outputs.hidden_states ) @add_start_docstrings( "\n ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n " ,UpperCAmelCase ,) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ,UpperCAmelCase ): '''simple docstring''' def __init__( self : Tuple , lowercase : Union[str, Any] ): '''simple docstring''' super().__init__(lowercase ) super()._init_backbone(lowercase ) _snake_case = [config.embedding_size] + config.hidden_sizes _snake_case = ResNetEmbeddings(lowercase ) _snake_case = ResNetEncoder(lowercase ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @replace_return_docstrings(output_type=lowercase , config_class=_CONFIG_FOR_DOC ) def A ( self : Dict , lowercase : Tensor , lowercase : Optional[bool] = None , lowercase : Optional[bool] = None ): '''simple docstring''' _snake_case = return_dict if return_dict is not None else self.config.use_return_dict _snake_case = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _snake_case = self.embedder(lowercase ) _snake_case = self.encoder(lowercase , output_hidden_states=lowercase , return_dict=lowercase ) _snake_case = outputs.hidden_states _snake_case = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: _snake_case = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=lowercase , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=lowercase , )
686
from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def a_ ( ) -> Optional[int]: _snake_case , _snake_case = 9, 14 # noqa: F841 _snake_case = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] _snake_case = defaultdict(__lowercase ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) _snake_case = mst(__lowercase ) _snake_case = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: _snake_case = tuple(answer[:2] ) _snake_case = tuple(edge[::-1] ) assert edge in result or reverse in result
686
1
"""simple docstring""" import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model __lowerCAmelCase : Optional[Any] = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def _UpperCAmelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ): """simple docstring""" if rng is None: lowerCAmelCase__ = random.Random() lowerCAmelCase__ = 1 for dim in shape: total_dims *= dim lowerCAmelCase__ = [] for _ in range(lowerCamelCase__ ): values.append(rng.randint(0 , vocab_size - 1 ) ) lowerCAmelCase__ = np.array(lowerCamelCase__ , dtype=jnp.intaa ).reshape(lowerCamelCase__ ) return output def _UpperCAmelCase ( lowerCamelCase__ , lowerCamelCase__=None ): """simple docstring""" lowerCAmelCase__ = ids_tensor(lowerCamelCase__ , vocab_size=2 , rng=lowerCamelCase__ ) # make sure that at least one token is attended to for each batch lowerCAmelCase__ = 1 return attn_mask @require_flax class a_ : UpperCamelCase_ : List[str] = None UpperCamelCase_ : Any = () def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 lowerCAmelCase__ = 2 lowerCAmelCase__ = inputs["""input_ids"""].shape[-1] // 2 lowerCAmelCase__ = inputs["""input_ids"""][:max_batch_size, :sequence_length] lowerCAmelCase__ = jnp.ones_like(snake_case__ ) lowerCAmelCase__ = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens lowerCAmelCase__ = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` lowerCAmelCase__ = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length lowerCAmelCase__ = 0 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCAmelCase__ = getattr(snake_case__ , snake_case__ ) lowerCAmelCase__ = pt_model_class(snake_case__ ).eval() lowerCAmelCase__ = load_flax_weights_in_pytorch_model(snake_case__ , flax_model.params ) lowerCAmelCase__ = flax_model.generate(snake_case__ ).sequences lowerCAmelCase__ = pt_model.generate(torch.tensor(snake_case__ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: lowerCAmelCase__ = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : int ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = True lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : str ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length lowerCAmelCase__ = 2 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _SCREAMING_SNAKE_CASE ( self : str ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = True lowerCAmelCase__ = max_length lowerCAmelCase__ = 0.8 lowerCAmelCase__ = 10 lowerCAmelCase__ = 0.3 lowerCAmelCase__ = 1 lowerCAmelCase__ = 8 lowerCAmelCase__ = 9 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : int ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = max_length lowerCAmelCase__ = 1 lowerCAmelCase__ = 8 lowerCAmelCase__ = 9 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = max_length lowerCAmelCase__ = 2 lowerCAmelCase__ = 1 lowerCAmelCase__ = 8 lowerCAmelCase__ = 9 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() # pad attention mask on the left lowerCAmelCase__ = attention_mask.at[(0, 0)].set(0 ) lowerCAmelCase__ = False lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ , attention_mask=snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ , attention_mask=snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() # pad attention mask on the left lowerCAmelCase__ = attention_mask.at[(0, 0)].set(0 ) lowerCAmelCase__ = True lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ , attention_mask=snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ , attention_mask=snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = self._get_input_ids_and_config() # pad attention mask on the left lowerCAmelCase__ = attention_mask.at[(0, 0)].set(0 ) lowerCAmelCase__ = 2 lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(snake_case__ ) lowerCAmelCase__ = model.generate(snake_case__ , attention_mask=snake_case__ ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(snake_case__ , attention_mask=snake_case__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class a_ ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): lowerCAmelCase__ = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) lowerCAmelCase__ = FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) lowerCAmelCase__ = """Hello world""" lowerCAmelCase__ = tokenizer(snake_case__ , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(snake_case__ , """do_samples""" ): model.generate(snake_case__ , do_samples=snake_case__ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(snake_case__ , """foo""" ): lowerCAmelCase__ = {"""foo""": """bar"""} model.generate(snake_case__ , **snake_case__ )
674
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class a_ ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): lowerCAmelCase__ = 0 def _SCREAMING_SNAKE_CASE ( self : List[Any] ): lowerCAmelCase__ = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase__ = Path(snake_case__ ) / """preprocessor_config.json""" lowerCAmelCase__ = Path(snake_case__ ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(snake_case__ , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(snake_case__ , """w""" ) ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase__ = Path(snake_case__ ) / """preprocessor_config.json""" lowerCAmelCase__ = Path(snake_case__ ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(snake_case__ , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(snake_case__ , """w""" ) ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase__ = CLIPConfig() # Create a dummy config file with image_proceesor_type lowerCAmelCase__ = Path(snake_case__ ) / """preprocessor_config.json""" lowerCAmelCase__ = Path(snake_case__ ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(snake_case__ , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(snake_case__ , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ ).to_dict() config_dict.pop("""image_processor_type""" ) lowerCAmelCase__ = CLIPImageProcessor(**snake_case__ ) # save in new folder model_config.save_pretrained(snake_case__ ) config.save_pretrained(snake_case__ ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ ) # make sure private variable is not incorrectly saved lowerCAmelCase__ = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE ( self : Dict ): with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase__ = Path(snake_case__ ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(snake_case__ , """w""" ) , ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): with self.assertRaisesRegex( snake_case__ , """clip-base is not a local folder and is not a valid model identifier""" ): lowerCAmelCase__ = AutoImageProcessor.from_pretrained("""clip-base""" ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): with self.assertRaisesRegex( snake_case__ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ , revision="""aaaaaa""" ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): with self.assertRaisesRegex( snake_case__ , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): lowerCAmelCase__ = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def _SCREAMING_SNAKE_CASE ( self : Any ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(snake_case__ ): lowerCAmelCase__ = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(snake_case__ ): lowerCAmelCase__ = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=snake_case__ ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=snake_case__ ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(snake_case__ ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ , trust_remote_code=snake_case__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def _SCREAMING_SNAKE_CASE ( self : Dict ): try: AutoConfig.register("""custom""" , snake_case__ ) AutoImageProcessor.register(snake_case__ , snake_case__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(snake_case__ ): AutoImageProcessor.register(snake_case__ , snake_case__ ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase__ = Path(snake_case__ ) / """preprocessor_config.json""" lowerCAmelCase__ = Path(snake_case__ ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(snake_case__ , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(snake_case__ , """w""" ) ) lowerCAmelCase__ = CustomImageProcessor.from_pretrained(snake_case__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(snake_case__ ) lowerCAmelCase__ = AutoImageProcessor.from_pretrained(snake_case__ ) self.assertIsInstance(snake_case__ , snake_case__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _SCREAMING_SNAKE_CASE ( self : List[str] ): class a_ ( __UpperCamelCase ): UpperCamelCase_ : Tuple = True try: AutoConfig.register("""custom""" , snake_case__ ) AutoImageProcessor.register(snake_case__ , snake_case__ ) # If remote code is not set, the default is to use local lowerCAmelCase__ = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. lowerCAmelCase__ = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=snake_case__ ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub lowerCAmelCase__ = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=snake_case__ ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(snake_case__ , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase = { """configuration_mega""": ["""MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MegaConfig""", """MegaOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ """MEGA_PRETRAINED_MODEL_ARCHIVE_LIST""", """MegaForCausalLM""", """MegaForMaskedLM""", """MegaForMultipleChoice""", """MegaForQuestionAnswering""", """MegaForSequenceClassification""", """MegaForTokenClassification""", """MegaModel""", """MegaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
104
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _A : Dict = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ : Any = BartphoTokenizer lowerCamelCase__ : Tuple = False lowerCamelCase__ : Dict = True def lowercase_ ( self ): '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE__ = ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] SCREAMING_SNAKE_CASE__ = dict(zip(A_ , range(len(A_ ) ) ) ) SCREAMING_SNAKE_CASE__ = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''monolingual_vocab_file'''] ) with open(self.monolingual_vocab_file , '''w''' , encoding='''utf-8''' ) as fp: for token in vocab_tokens: fp.write(f'''{token} {vocab_tokens[token]}\n''' ) SCREAMING_SNAKE_CASE__ = BartphoTokenizer(A_ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase_ ( self , **A_ ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **A_ ) def lowercase_ ( self , A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = '''This is a là test''' SCREAMING_SNAKE_CASE__ = '''This is a<unk><unk> test''' return input_text, output_text def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = BartphoTokenizer(A_ , self.monolingual_vocab_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ = '''This is a là test''' SCREAMING_SNAKE_CASE__ = '''▁This ▁is ▁a ▁l à ▁t est'''.split() SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) SCREAMING_SNAKE_CASE__ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ )
100
0
'''simple docstring''' from collections.abc import Generator def _SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ : List[str] = 0, 1 while True: lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = b, a + b yield b def _SCREAMING_SNAKE_CASE ( UpperCamelCase = 1000 ): """simple docstring""" lowerCAmelCase__ : Dict = 1 lowerCAmelCase__ : Optional[Any] = fibonacci_generator() while len(str(next(UpperCamelCase ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
711
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _SCREAMING_SNAKE_CASE ( *UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): lowerCAmelCase__ : List[Any] = list(UpperCamelCase ) for i in range(len(UpperCamelCase ) ): lowerCAmelCase__ : Dict = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Union[str, Any] = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(UpperCamelCase , UpperCamelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _SCREAMING_SNAKE_CASE ( UpperCamelCase = None , UpperCamelCase = 128 ): """simple docstring""" if function is None: return functools.partial(UpperCamelCase , starting_batch_size=UpperCamelCase ) lowerCAmelCase__ : Any = starting_batch_size def decorator(*UpperCamelCase , **UpperCamelCase ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() lowerCAmelCase__ : Optional[Any] = list(inspect.signature(UpperCamelCase ).parameters.keys() ) # Guard against user error if len(UpperCamelCase ) < (len(UpperCamelCase ) + 1): lowerCAmelCase__ : Any = """, """.join([f"""{arg}={value}""" for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( f"""Batch size was passed into `{function.__name__}` as the first argument when called.""" f"""Remove this as the decorator already does so: `{function.__name__}({arg_str})`""" ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(UpperCamelCase , *UpperCamelCase , **UpperCamelCase ) except Exception as e: if should_reduce_batch_size(UpperCamelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
160
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowerCAmelCase__ = random.Random() if is_torch_available(): import torch def snake_case_ ( A_ : Tuple, A_ : List[Any]=1.0, A_ : Optional[Any]=None, A_ : Optional[int]=None ): '''simple docstring''' if rng is None: _lowerCamelCase : Dict = global_rng _lowerCamelCase : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __snake_case ( unittest.TestCase): def __init__( self : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any]=7 , __lowerCAmelCase : int=4_0_0 , __lowerCAmelCase : List[str]=2_0_0_0 , __lowerCAmelCase : str=1 , __lowerCAmelCase : Tuple=0.0 , __lowerCAmelCase : Dict=1_6_0_0_0 , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Any=True , ): """simple docstring""" _lowerCamelCase : int = parent _lowerCamelCase : Optional[Any] = batch_size _lowerCamelCase : int = min_seq_length _lowerCamelCase : Any = max_seq_length _lowerCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _lowerCamelCase : Dict = feature_size _lowerCamelCase : int = padding_value _lowerCamelCase : Tuple = sampling_rate _lowerCamelCase : Optional[int] = return_attention_mask _lowerCamelCase : List[str] = do_normalize def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Any=False , __lowerCAmelCase : int=False ): """simple docstring""" def _flatten(__lowerCAmelCase : int ): return list(itertools.chain(*__lowerCAmelCase ) ) if equal_length: _lowerCamelCase : str = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size _lowerCamelCase : Optional[Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _lowerCamelCase : Dict = [np.asarray(__lowerCAmelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __snake_case ( _lowercase , unittest.TestCase): snake_case__ : List[str] = ASTFeatureExtractor def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ASTFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _lowerCamelCase : List[str] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _lowerCamelCase : Tuple = [np.asarray(__lowerCAmelCase ) for speech_input in speech_inputs] # Test not batched input _lowerCamelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values _lowerCamelCase : Optional[int] = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # Test batched _lowerCamelCase : Optional[Any] = feat_extract(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_values _lowerCamelCase : Optional[Any] = feat_extract(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. _lowerCamelCase : str = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _lowerCamelCase : Any = np.asarray(__lowerCAmelCase ) _lowerCamelCase : Dict = feat_extract(__lowerCAmelCase , return_tensors='''np''' ).input_values _lowerCamelCase : List[Any] = feat_extract(__lowerCAmelCase , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) @require_torch def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" import torch _lowerCamelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _lowerCamelCase : Any = np.random.rand(1_0_0 ).astype(np.floataa ) _lowerCamelCase : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _lowerCamelCase : Union[str, Any] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) _lowerCamelCase : Tuple = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : List[str] ): """simple docstring""" from datasets import load_dataset _lowerCamelCase : str = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech _lowerCamelCase : int = ds.sort('''id''' ).select(range(__lowerCAmelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on _lowerCamelCase : Optional[Any] = self._load_datasamples(1 ) _lowerCamelCase : int = ASTFeatureExtractor() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , __lowerCAmelCase , atol=1E-4 ) )
83
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ): '''simple docstring''' _lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {} _lowerCamelCase : Union[str, Any] = padding_side return tokenizer( [line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, ) def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ): '''simple docstring''' _lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ): """simple docstring""" super().__init__() _lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' ) _lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' ) _lowerCamelCase : List[Any] = self.get_char_lens(self.src_file ) _lowerCamelCase : Optional[int] = max_source_length _lowerCamelCase : Optional[Any] = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _lowerCamelCase : List[Any] = tokenizer _lowerCamelCase : List[Any] = prefix if n_obs is not None: _lowerCamelCase : List[str] = self.src_lens[:n_obs] _lowerCamelCase : int = src_lang _lowerCamelCase : Union[str, Any] = tgt_lang def __len__( self : int ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = index + 1 # linecache starts at 1 _lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' ) _lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowerCAmelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _lowerCamelCase : Optional[int] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer ) _lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' ) _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' ) _lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze() _lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() _lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ): """simple docstring""" return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) _lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowerCAmelCase__ = getLogger(__name__) def snake_case_ ( A_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(A_ ) ) def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Dict = get_git_info() save_json(A_, os.path.join(A_, '''git_log.json''' ) ) def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ): '''simple docstring''' with open(A_, '''w''' ) as f: json.dump(A_, A_, indent=A_, **A_ ) def snake_case_ ( A_ : Any ): '''simple docstring''' with open(A_ ) as f: return json.load(A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ ) _lowerCamelCase : str = { '''repo_id''': str(A_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case_ ( A_ : Callable, A_ : Iterable ): '''simple docstring''' return list(map(A_, A_ ) ) def snake_case_ ( A_ : str, A_ : Tuple ): '''simple docstring''' with open(A_, '''wb''' ) as f: return pickle.dump(A_, A_ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' def remove_articles(A_ : str ): return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ ) def white_space_fix(A_ : Any ): return " ".join(text.split() ) def remove_punc(A_ : List[Any] ): _lowerCamelCase : Any = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case_ ( A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : str = normalize_answer(A_ ).split() _lowerCamelCase : int = normalize_answer(A_ ).split() _lowerCamelCase : str = Counter(A_ ) & Counter(A_ ) _lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 _lowerCamelCase : int = 1.0 * num_same / len(A_ ) _lowerCamelCase : str = 1.0 * num_same / len(A_ ) _lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case_ ( A_ : Dict, A_ : str ): '''simple docstring''' return normalize_answer(A_ ) == normalize_answer(A_ ) def snake_case_ ( A_ : List[str], A_ : List[str] ): '''simple docstring''' assert len(A_ ) == len(A_ ) _lowerCamelCase : Optional[Any] = 0 for hypo, pred in zip(A_, A_ ): em += exact_match_score(A_, A_ ) if len(A_ ) > 0: em /= len(A_ ) return {"em": em} def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Dict = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _lowerCamelCase : Tuple = '''dropout_rate''' for p in extra_params: if getattr(A_, A_, A_ ): if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) ) delattr(A_, A_ ) continue _lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p] setattr(A_, A_, getattr(A_, A_ ) ) delattr(A_, A_ ) return hparams, config
83
1
"""simple docstring""" from math import factorial lowerCamelCase__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def __A ( a_ : List[Any] )-> int: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): 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(__lowerCAmelCase ) ) def __A ( a_ : Tuple = 60 , a_ : List[str] = 1_00_00_00 )-> int: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): 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 SCREAMING_SNAKE_CASE : str = 0 # the cached sizes of the previous chains SCREAMING_SNAKE_CASE : dict[int, int] = {} for start_chain_element in range(1 , __lowerCAmelCase ): # The temporary set will contain the elements of the chain SCREAMING_SNAKE_CASE : Optional[Any] = set() SCREAMING_SNAKE_CASE : List[str] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. SCREAMING_SNAKE_CASE : str = 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(__lowerCAmelCase ) chain_set_length += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = digit_factorial_sum(__lowerCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] SCREAMING_SNAKE_CASE : str = 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()}''')
712
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging lowerCamelCase__ : Tuple = logging.get_logger(__name__) lowerCamelCase__ : str = { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class lowercase__( _UpperCAmelCase ): '''simple docstring''' UpperCamelCase = """blenderbot-small""" UpperCamelCase = ["""past_key_values"""] UpperCamelCase = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self :Any , lowerCamelCase_ :Dict=5_02_65 , lowerCamelCase_ :str=5_12 , lowerCamelCase_ :Tuple=8 , lowerCamelCase_ :int=20_48 , lowerCamelCase_ :str=16 , lowerCamelCase_ :Optional[int]=8 , lowerCamelCase_ :str=20_48 , lowerCamelCase_ :Optional[Any]=16 , lowerCamelCase_ :Union[str, Any]=0.0 , lowerCamelCase_ :List[str]=0.0 , lowerCamelCase_ :Tuple=True , lowerCamelCase_ :Tuple=True , lowerCamelCase_ :int="gelu" , lowerCamelCase_ :Tuple=5_12 , lowerCamelCase_ :Optional[int]=0.1 , lowerCamelCase_ :int=0.0 , lowerCamelCase_ :Tuple=0.0 , lowerCamelCase_ :Optional[int]=0.0_2 , lowerCamelCase_ :Union[str, Any]=1 , lowerCamelCase_ :Dict=False , lowerCamelCase_ :Optional[int]=0 , lowerCamelCase_ :List[Any]=1 , lowerCamelCase_ :Any=2 , lowerCamelCase_ :Optional[Any]=2 , **lowerCamelCase_ :Dict , ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[Any] = d_model SCREAMING_SNAKE_CASE : Dict = encoder_ffn_dim SCREAMING_SNAKE_CASE : Tuple = encoder_layers SCREAMING_SNAKE_CASE : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE : Any = decoder_ffn_dim SCREAMING_SNAKE_CASE : str = decoder_layers SCREAMING_SNAKE_CASE : str = decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE : Any = activation_dropout SCREAMING_SNAKE_CASE : List[str] = activation_function SCREAMING_SNAKE_CASE : Optional[int] = init_std SCREAMING_SNAKE_CASE : List[Any] = encoder_layerdrop SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_layerdrop SCREAMING_SNAKE_CASE : List[Any] = use_cache SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_layers SCREAMING_SNAKE_CASE : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , is_encoder_decoder=lowerCamelCase_ , decoder_start_token_id=lowerCamelCase_ , forced_eos_token_id=lowerCamelCase_ , **lowerCamelCase_ , ) class lowercase__( _UpperCAmelCase ): '''simple docstring''' @property def __lowerCAmelCase ( self :Any ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE : Tuple = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: SCREAMING_SNAKE_CASE : Union[str, Any] = {0: '''batch'''} SCREAMING_SNAKE_CASE : List[Any] = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: SCREAMING_SNAKE_CASE : Optional[Any] = {0: '''batch''', 1: '''decoder_sequence'''} SCREAMING_SNAKE_CASE : Union[str, Any] = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase_ , direction='''inputs''' ) elif self.task == "causal-lm": # TODO: figure this case out. SCREAMING_SNAKE_CASE : Tuple = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = self.num_layers for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = {0: '''batch''', 2: '''past_sequence + sequence'''} SCREAMING_SNAKE_CASE : List[str] = {0: '''batch''', 2: '''past_sequence + sequence'''} else: SCREAMING_SNAKE_CASE : Any = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}), ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}), ] ) return common_inputs @property def __lowerCAmelCase ( self :List[str] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE : Any = super().outputs else: SCREAMING_SNAKE_CASE : Tuple = super(lowerCamelCase_ , self ).outputs if self.use_past: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_layers for i in range(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = {0: '''batch''', 2: '''past_sequence + sequence'''} SCREAMING_SNAKE_CASE : str = {0: '''batch''', 2: '''past_sequence + sequence'''} return common_outputs def __lowerCAmelCase ( self :int , lowerCamelCase_ :PreTrainedTokenizer , lowerCamelCase_ :int = -1 , lowerCamelCase_ :int = -1 , lowerCamelCase_ :bool = False , lowerCamelCase_ :Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Generate decoder inputs SCREAMING_SNAKE_CASE : Optional[int] = seq_length if not self.use_past else 1 SCREAMING_SNAKE_CASE : Optional[int] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} SCREAMING_SNAKE_CASE : str = dict(**lowerCamelCase_ , **lowerCamelCase_ ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = common_inputs['''input_ids'''].shape SCREAMING_SNAKE_CASE : str = common_inputs['''decoder_input_ids'''].shape[1] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = self.num_attention_heads SCREAMING_SNAKE_CASE : str = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) SCREAMING_SNAKE_CASE : Optional[Any] = decoder_seq_length + 3 SCREAMING_SNAKE_CASE : int = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) SCREAMING_SNAKE_CASE : List[Any] = torch.cat( [common_inputs['''decoder_attention_mask'''], torch.ones(lowerCamelCase_ , lowerCamelCase_ )] , dim=1 ) SCREAMING_SNAKE_CASE : Optional[int] = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = self.num_layers SCREAMING_SNAKE_CASE : int = min(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = max(lowerCamelCase_ , lowerCamelCase_ ) - min_num_layers SCREAMING_SNAKE_CASE : Tuple = '''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder''' for _ in range(lowerCamelCase_ ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCamelCase_ ), torch.zeros(lowerCamelCase_ ), torch.zeros(lowerCamelCase_ ), torch.zeros(lowerCamelCase_ ), ) ) # TODO: test this. SCREAMING_SNAKE_CASE : int = encoder_shape if remaining_side_name == '''encoder''' else decoder_shape for _ in range(lowerCamelCase_ , lowerCamelCase_ ): common_inputs["past_key_values"].append((torch.zeros(lowerCamelCase_ ), torch.zeros(lowerCamelCase_ )) ) return common_inputs def __lowerCAmelCase ( self :Any , lowerCamelCase_ :PreTrainedTokenizer , lowerCamelCase_ :int = -1 , lowerCamelCase_ :int = -1 , lowerCamelCase_ :bool = False , lowerCamelCase_ :Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Tuple = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE : List[str] = seqlen + 2 SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Dict = self.num_layers SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[Any] = self.num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) SCREAMING_SNAKE_CASE : Tuple = common_inputs['''attention_mask'''].dtype SCREAMING_SNAKE_CASE : Any = torch.cat( [common_inputs['''attention_mask'''], torch.ones(lowerCamelCase_ , lowerCamelCase_ , dtype=lowerCamelCase_ )] , dim=1 ) SCREAMING_SNAKE_CASE : Optional[int] = [ (torch.zeros(lowerCamelCase_ ), torch.zeros(lowerCamelCase_ )) for _ in range(lowerCamelCase_ ) ] return common_inputs def __lowerCAmelCase ( self :Union[str, Any] , lowerCamelCase_ :PreTrainedTokenizer , lowerCamelCase_ :int = -1 , lowerCamelCase_ :int = -1 , lowerCamelCase_ :bool = False , lowerCamelCase_ :Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = compute_effective_axis_dimension( lowerCamelCase_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE : int = tokenizer.num_special_tokens_to_add(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = compute_effective_axis_dimension( lowerCamelCase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase_ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE : Tuple = [''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size SCREAMING_SNAKE_CASE : Any = dict(tokenizer(lowerCamelCase_ , return_tensors=lowerCamelCase_ ) ) return common_inputs def __lowerCAmelCase ( self :List[Any] , lowerCamelCase_ :PreTrainedTokenizer , lowerCamelCase_ :int = -1 , lowerCamelCase_ :int = -1 , lowerCamelCase_ :bool = False , lowerCamelCase_ :Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE : Dict = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCamelCase_ , batch_size=lowerCamelCase_ , seq_length=lowerCamelCase_ , is_pair=lowerCamelCase_ , framework=lowerCamelCase_ ) elif self.task == "causal-lm": SCREAMING_SNAKE_CASE : Union[str, Any] = self._generate_dummy_inputs_for_causal_lm( lowerCamelCase_ , batch_size=lowerCamelCase_ , seq_length=lowerCamelCase_ , is_pair=lowerCamelCase_ , framework=lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase_ , batch_size=lowerCamelCase_ , seq_length=lowerCamelCase_ , is_pair=lowerCamelCase_ , framework=lowerCamelCase_ ) return common_inputs def __lowerCAmelCase ( self :Dict , lowerCamelCase_ :int , lowerCamelCase_ :List[str] , lowerCamelCase_ :List[str] , lowerCamelCase_ :Dict ) -> List[Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE : Optional[Any] = super()._flatten_past_key_values_(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: SCREAMING_SNAKE_CASE : Tuple = super(lowerCamelCase_ , self )._flatten_past_key_values_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
18
0
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="""%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s""", datefmt="""%Y-%m-%d %H:%M:%S""", level=os.environ.get("""LOGLEVEL""", """INFO""").upper(), stream=sys.stdout, ) __lowerCamelCase = logging.getLogger(__name__) __lowerCamelCase = {'facebook/bart-base': BartForConditionalGeneration} __lowerCamelCase = {'facebook/bart-base': BartTokenizer} def UpperCamelCase ( ): snake_case : Any = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=_UpperCAmelCase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=_UpperCAmelCase , default=_UpperCAmelCase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=_UpperCAmelCase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=_UpperCAmelCase , ) parser.add_argument( "--config_name" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=_UpperCAmelCase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="Where to store the final ONNX file." ) snake_case : Optional[int] = parser.parse_args() return args def UpperCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Optional[int]="cpu" ): snake_case : Optional[int] = model_dict[model_name].from_pretrained(_UpperCAmelCase ).to(_UpperCAmelCase ) snake_case : Optional[int] = tokenizer_dict[model_name].from_pretrained(_UpperCAmelCase ) if model_name in ["facebook/bart-base"]: snake_case : Any = 0 snake_case : int = None snake_case : Union[str, Any] = 0 return huggingface_model, tokenizer def UpperCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : int ): model.eval() snake_case : Tuple = None snake_case : List[Any] = torch.jit.script(BARTBeamSearchGenerator(_UpperCAmelCase ) ) with torch.no_grad(): snake_case : Optional[int] = "My friends are cool but they eat too many carbs." snake_case : Optional[Any] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) snake_case : Any = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=_UpperCAmelCase , max_length=_UpperCAmelCase , early_stopping=_UpperCAmelCase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( _UpperCAmelCase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , _UpperCAmelCase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=_UpperCAmelCase , ) logger.info("Model exported to {}".format(_UpperCAmelCase ) ) snake_case : List[str] = remove_dup_initializers(os.path.abspath(_UpperCAmelCase ) ) logger.info("Deduplicated and optimized model written to {}".format(_UpperCAmelCase ) ) snake_case : Optional[int] = onnxruntime.InferenceSession(_UpperCAmelCase ) snake_case : List[str] = ort_sess.run( _UpperCAmelCase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(_UpperCAmelCase ), "max_length": np.array(_UpperCAmelCase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def UpperCamelCase ( ): snake_case : Tuple = parse_args() snake_case : Dict = 5 snake_case : List[Any] = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() snake_case : List[str] = torch.device(args.device ) snake_case , snake_case : Any = load_model_tokenizer(args.model_name_or_path , _UpperCAmelCase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(_UpperCAmelCase ) if args.max_length: snake_case : int = args.max_length if args.num_beams: snake_case : List[Any] = args.num_beams if args.output_file_path: snake_case : Dict = args.output_file_path else: snake_case : Union[str, Any] = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
204
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' def __a ( A__ , A__ , A__ ) -> list: lowerCAmelCase = len(A__ ) lowerCAmelCase = [[0] * n for i in range(A__ )] for i in range(A__ ): lowerCAmelCase = y_points[i] for i in range(2 , A__ ): for j in range(A__ , A__ ): lowerCAmelCase = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
159
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch lowercase : Optional[int] = random.Random() def __a ( A__ , A__=1.0 , A__=None , A__=None ) -> Any: if rng is None: lowerCAmelCase = global_rng lowerCAmelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int=7 , SCREAMING_SNAKE_CASE : Optional[Any]=4_0_0 , SCREAMING_SNAKE_CASE : Optional[Any]=2_0_0_0 , SCREAMING_SNAKE_CASE : Union[str, Any]=1 , SCREAMING_SNAKE_CASE : int=0.0 , SCREAMING_SNAKE_CASE : Optional[int]=1_6_0_0_0 , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : Optional[Any]=8_0 , SCREAMING_SNAKE_CASE : int=1_6 , SCREAMING_SNAKE_CASE : Any=6_4 , SCREAMING_SNAKE_CASE : List[Any]="hann_window" , SCREAMING_SNAKE_CASE : Dict=8_0 , SCREAMING_SNAKE_CASE : Any=7_6_0_0 , SCREAMING_SNAKE_CASE : Optional[Any]=1E-10 , SCREAMING_SNAKE_CASE : Union[str, Any]=True , ) -> Any: """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = min_seq_length lowerCAmelCase = max_seq_length lowerCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCAmelCase = feature_size lowerCAmelCase = padding_value lowerCAmelCase = sampling_rate lowerCAmelCase = do_normalize lowerCAmelCase = num_mel_bins lowerCAmelCase = hop_length lowerCAmelCase = win_length lowerCAmelCase = win_function lowerCAmelCase = fmin lowerCAmelCase = fmax lowerCAmelCase = mel_floor lowerCAmelCase = return_attention_mask def __A ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __A ( self : List[str] , SCREAMING_SNAKE_CASE : int=False , SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> str: """simple docstring""" def _flatten(SCREAMING_SNAKE_CASE : List[Any] ): return list(itertools.chain(*SCREAMING_SNAKE_CASE ) ) if equal_length: lowerCAmelCase = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size lowerCAmelCase = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs def __A ( self : List[str] , SCREAMING_SNAKE_CASE : Tuple=False , SCREAMING_SNAKE_CASE : Optional[int]=False ) -> str: """simple docstring""" if equal_length: lowerCAmelCase = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowerCAmelCase = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch class _lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" lowerCAmelCase = SpeechTaFeatureExtractor def __A ( self : Optional[int] ) -> Dict: """simple docstring""" lowerCAmelCase = SpeechTaFeatureExtractionTester(self ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE , axis=0 ) - 1 ) < 1E-3 ) ) def __A ( self : int ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test not batched input lowerCAmelCase = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values lowerCAmelCase = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def __A ( self : Any ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = ["longest", "max_length", "do_not_pad"] lowerCAmelCase = [None, 1_6_0_0, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def __A ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = range(8_0_0 , 1_4_0_0 , 2_0_0 ) lowerCAmelCase = [floats_list((1, x) )[0] for x in lengths] lowerCAmelCase = ["longest", "max_length", "do_not_pad"] lowerCAmelCase = [None, 1_6_0_0, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def __A ( self : str ) -> Any: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = feat_extract( SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=1_0_0_0 , padding="max_length" , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __A ( self : int ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = feat_extract( SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=1_0_0_0 , padding="longest" , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = feat_extract( SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=2_0_0_0 , padding="longest" , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) def __A ( self : Optional[int] ) -> Any: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = np.random.rand(1_0_0 ).astype(np.floataa ) lowerCAmelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCAmelCase = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) lowerCAmelCase = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __A ( self : int ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size lowerCAmelCase = feature_extractor(audio_target=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input lowerCAmelCase = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_values lowerCAmelCase = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. lowerCAmelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] lowerCAmelCase = np.asarray(SCREAMING_SNAKE_CASE ) lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def __A ( self : Dict ) -> Optional[Any]: """simple docstring""" lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) for x, y in zip(SCREAMING_SNAKE_CASE , processed_features[input_name] ) ) ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE ) lowerCAmelCase = BatchFeature({input_name: speech_inputs} , tensor_type="np" ) lowerCAmelCase = processed_features[input_name] if len(batch_features_input.shape ) < 3: lowerCAmelCase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __A ( self : List[str] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} , tensor_type="pt" ) lowerCAmelCase = processed_features[input_name] if len(batch_features_input.shape ) < 3: lowerCAmelCase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __A ( self : Optional[int] ) -> Dict: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) lowerCAmelCase = feat_extract.num_mel_bins # hack! lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="np" )[input_name] lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="pt" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __A ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.feat_extract_dict lowerCAmelCase = True lowerCAmelCase = self.feature_extraction_class(**SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs] lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) lowerCAmelCase = feat_extract.num_mel_bins # hack! lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="np" ) self.assertIn("attention_mask" , SCREAMING_SNAKE_CASE ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE ) def __A ( self : Tuple ) -> List[Any]: """simple docstring""" lowerCAmelCase = self.feat_extract_dict lowerCAmelCase = True lowerCAmelCase = self.feature_extraction_class(**SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs] lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) lowerCAmelCase = min(SCREAMING_SNAKE_CASE ) lowerCAmelCase = feat_extract.num_mel_bins # hack! lowerCAmelCase = feat_extract.pad( SCREAMING_SNAKE_CASE , padding="max_length" , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors="np" ) self.assertIn("attention_mask" , SCREAMING_SNAKE_CASE ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" from datasets import load_dataset lowerCAmelCase = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech lowerCAmelCase = ds.sort("id" ).select(range(SCREAMING_SNAKE_CASE ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ) -> int: """simple docstring""" lowerCAmelCase = torch.tensor( [2.38_04E-03, 2.07_52E-03, 1.98_36E-03, 2.10_57E-03, 1.61_74E-03, 3.05_18E-04, 9.15_53E-05, 3.35_69E-04, 9.76_56E-04, 1.83_11E-03, 2.01_42E-03, 2.10_57E-03, 1.73_95E-03, 4.57_76E-04, -3.96_73E-04, 4.57_76E-04, 1.00_71E-03, 9.15_53E-05, 4.88_28E-04, 1.15_97E-03, 7.32_42E-04, 9.46_04E-04, 1.80_05E-03, 1.83_11E-03, 8.85_01E-04, 4.27_25E-04, 4.88_28E-04, 7.32_42E-04, 1.09_86E-03, 2.10_57E-03] ) # fmt: on lowerCAmelCase = self._load_datasamples(1 ) lowerCAmelCase = SpeechTaFeatureExtractor() lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 9_3_6_8_0) ) self.assertTrue(torch.allclose(input_values[0, :3_0] , SCREAMING_SNAKE_CASE , atol=1E-6 ) ) def __A ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = torch.tensor( [-2.6_8_7_0, -3.0_1_0_4, -3.1_3_5_6, -3.5_3_5_2, -3.0_0_4_4, -3.0_3_5_3, -3.4_7_1_9, -3.6_7_7_7, -3.1_5_2_0, -2.9_4_3_5, -2.6_5_5_3, -2.8_7_9_5, -2.9_9_4_4, -2.5_9_2_1, -3.0_2_7_9, -3.0_3_8_6, -3.0_8_6_4, -3.1_2_9_1, -3.2_3_5_3, -2.7_4_4_4, -2.6_8_3_1, -2.7_2_8_7, -3.1_7_6_1, -3.1_5_7_1, -3.2_7_2_6, -3.0_5_8_2, -3.1_0_0_7, -3.4_5_3_3, -3.4_6_9_5, -3.0_9_9_8] ) # fmt: on lowerCAmelCase = self._load_datasamples(1 ) lowerCAmelCase = SpeechTaFeatureExtractor() lowerCAmelCase = feature_extractor(audio_target=SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 3_6_6, 8_0) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , SCREAMING_SNAKE_CASE , atol=1E-4 ) )
159
1
'''simple docstring''' import math def A__ ( UpperCAmelCase_ ): _UpperCamelCase : Any = [] _UpperCamelCase : List[str] = 2 _UpperCamelCase : Dict = int(math.sqrt(UpperCAmelCase_ ) ) # Size of every segment _UpperCamelCase : Tuple = [True] * (end + 1) _UpperCamelCase : Dict = [] while start <= end: if temp[start] is True: in_prime.append(UpperCAmelCase_ ) for i in range(start * start , end + 1 , UpperCAmelCase_ ): _UpperCamelCase : Optional[int] = False start += 1 prime += in_prime _UpperCamelCase : str = end + 1 _UpperCamelCase : Optional[Any] = min(2 * end , UpperCAmelCase_ ) while low <= n: _UpperCamelCase : Dict = [True] * (high - low + 1) for each in in_prime: _UpperCamelCase : int = math.floor(low / each ) * each if t < low: t += each for j in range(UpperCAmelCase_ , high + 1 , UpperCAmelCase_ ): _UpperCamelCase : Optional[int] = False for j in range(len(UpperCAmelCase_ ) ): if temp[j] is True: prime.append(j + low ) _UpperCamelCase : List[str] = high + 1 _UpperCamelCase : List[str] = min(high + end , UpperCAmelCase_ ) return prime print(sieve(10**6))
195
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , _A : int , _A : Any=7 , _A : List[str]=3 , _A : Optional[Any]=18 , _A : List[str]=30 , _A : Optional[Any]=400 , _A : Any=True , _A : List[str]=None , _A : Union[str, Any]=True , _A : Optional[int]=None , ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = size if size is not None else {'''shortest_edge''': 20} __SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} __SCREAMING_SNAKE_CASE : int = parent __SCREAMING_SNAKE_CASE : Optional[int] = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = num_channels __SCREAMING_SNAKE_CASE : List[str] = image_size __SCREAMING_SNAKE_CASE : int = min_resolution __SCREAMING_SNAKE_CASE : Optional[int] = max_resolution __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : str = do_center_crop __SCREAMING_SNAKE_CASE : Any = crop_size def UpperCAmelCase__ ( self : Dict ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class __UpperCamelCase ( lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = MobileNetVaImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = MobileNetVaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_center_crop''' ) ) self.assertTrue(hasattr(_A , '''crop_size''' ) ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def UpperCAmelCase__ ( self : int ): """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = 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=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Any = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Dict = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
74
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo _lowercase: List[Any] = '''\ @misc{wu2016googles, title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } ''' _lowercase: List[Any] = '''\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the \'GLEU score\'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score\'s range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. ''' _lowercase: List[Any] = '''\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: \'google_bleu\': google_bleu score Examples: Example 1: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.44 Example 2: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.61 Example 3: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results["google_bleu"], 2)) 0.53 Example 4: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results["google_bleu"], 2)) 0.4 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowerCamelCase__ ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ) , id='references' ), } ) , ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , lowercase__ : List[List[List[str]]] , lowercase__ : List[List[str]] , lowercase__ : int = 1 , lowercase__ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=lowercase__ , hypotheses=lowercase__ , min_len=lowercase__ , max_len=lowercase__ ) }
702
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCamelCase__ ( UpperCAmelCase ): @staticmethod @abstractmethod def SCREAMING_SNAKE_CASE__ ( lowercase__ : ArgumentParser ): raise NotImplementedError() @abstractmethod def SCREAMING_SNAKE_CASE__ ( self : Dict ): raise NotImplementedError()
225
0
from __future__ import annotations __A : List[str] = 1.6021e-19 # units = C def __a ( A__ : float , A__ : float , A__ : float , ): if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
16
"""simple docstring""" from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE__ : lowercase__ = 42 lowercase__ = None lowercase__ = None UpperCAmelCase : Dict = namedtuple("CoinsDistribResult", "moves excess") def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(__lowerCAmelCase ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(__lowerCAmelCase ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(__lowerCAmelCase ) != count_coins(__lowerCAmelCase ): raise ValueError("""The nodes number should be same as the number of coins""" ) # Main calculation def get_distrib(__lowerCAmelCase ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowercase_ , lowercase_ = get_distrib(node.left ) lowercase_ , lowercase_ = get_distrib(node.right ) lowercase_ = 1 - left_distrib_excess lowercase_ = 1 - right_distrib_excess lowercase_ = ( left_distrib_moves + right_distrib_moves + abs(__lowerCAmelCase ) + abs(__lowerCAmelCase ) ) lowercase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(__lowerCAmelCase , __lowerCAmelCase ) return get_distrib(__lowerCAmelCase )[0] if __name__ == "__main__": import doctest doctest.testmod()
567
0
import sys import turtle def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> tuple[float, float]: """simple docstring""" return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,) -> None: """simple docstring""" my_pen.up() my_pen.goto(vertexa[0] ,vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] ,vertexa[1] ) my_pen.goto(vertexa[0] ,vertexa[1] ) my_pen.goto(vertexa[0] ,vertexa[1] ) if depth == 0: return triangle(_lowerCAmelCase ,get_mid(_lowerCAmelCase ,_lowerCAmelCase ) ,get_mid(_lowerCAmelCase ,_lowerCAmelCase ) ,depth - 1 ) triangle(_lowerCAmelCase ,get_mid(_lowerCAmelCase ,_lowerCAmelCase ) ,get_mid(_lowerCAmelCase ,_lowerCAmelCase ) ,depth - 1 ) triangle(_lowerCAmelCase ,get_mid(_lowerCAmelCase ,_lowerCAmelCase ) ,get_mid(_lowerCAmelCase ,_lowerCAmelCase ) ,depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( '''Correct format for using this script: ''' '''python fractals.py <int:depth_for_fractal>''' ) UpperCamelCase = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('''red''') UpperCamelCase = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
716
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class __UpperCAmelCase (TensorFormatter[Mapping, "torch.Tensor", Mapping] ): def __init__( self: str , UpperCAmelCase_: Union[str, Any]=None , **UpperCAmelCase_: Dict ): '''simple docstring''' super().__init__(features=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = torch_tensor_kwargs import torch # noqa import torch at initialization def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: Optional[int] ): '''simple docstring''' import torch if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and column: if all( isinstance(UpperCAmelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(UpperCAmelCase_ ) return column def UpperCamelCase ( self: int , UpperCAmelCase_: Optional[int] ): '''simple docstring''' import torch if isinstance(UpperCAmelCase_ , (str, bytes, type(UpperCAmelCase_ )) ): return value elif isinstance(UpperCAmelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _SCREAMING_SNAKE_CASE = {} if isinstance(UpperCAmelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): _SCREAMING_SNAKE_CASE = {"""dtype""": torch.intaa} elif isinstance(UpperCAmelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _SCREAMING_SNAKE_CASE = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(UpperCAmelCase_ , PIL.Image.Image ): _SCREAMING_SNAKE_CASE = np.asarray(UpperCAmelCase_ ) return torch.tensor(UpperCAmelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def UpperCamelCase ( self: Tuple , UpperCAmelCase_: str ): '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(UpperCAmelCase_ , """__array__""" ) and not isinstance(UpperCAmelCase_ , torch.Tensor ): _SCREAMING_SNAKE_CASE = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(UpperCAmelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(UpperCAmelCase_ ) for substruct in data_struct] ) elif isinstance(UpperCAmelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(UpperCAmelCase_ ) for substruct in data_struct] ) return self._tensorize(UpperCAmelCase_ ) def UpperCamelCase ( self: Dict , UpperCAmelCase_: dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , UpperCAmelCase_ , map_list=UpperCAmelCase_ ) def UpperCamelCase ( self: str , UpperCAmelCase_: pa.Table ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.numpy_arrow_extractor().extract_row(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.python_features_decoder.decode_row(UpperCAmelCase_ ) return self.recursive_tensorize(UpperCAmelCase_ ) def UpperCamelCase ( self: Any , UpperCAmelCase_: pa.Table ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.numpy_arrow_extractor().extract_column(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.python_features_decoder.decode_column(UpperCAmelCase_ , pa_table.column_names[0] ) _SCREAMING_SNAKE_CASE = self.recursive_tensorize(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self._consolidate(UpperCAmelCase_ ) return column def UpperCamelCase ( self: str , UpperCAmelCase_: pa.Table ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.numpy_arrow_extractor().extract_batch(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.python_features_decoder.decode_batch(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.recursive_tensorize(UpperCAmelCase_ ) for column_name in batch: _SCREAMING_SNAKE_CASE = self._consolidate(batch[column_name] ) return batch
569
0
"""simple docstring""" def snake_case ( A__ ,A__ ): if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) UpperCAmelCase_ : str = str(bin(A__ ) )[2:] # remove the leading "0b" UpperCAmelCase_ : Optional[int] = str(bin(A__ ) )[2:] # remove the leading "0b" UpperCAmelCase_ : str = max(len(A__ ) ,len(A__ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(A__ ) ,b_binary.zfill(A__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
95
"""simple docstring""" def A ( __snake_case: int = 1_0_0_0_0_0_0 ) -> int: """simple docstring""" __magic_name__ = limit + 1 __magic_name__ = [0] * limit for first_term in range(1 , __snake_case ): for n in range(__snake_case , __snake_case , __snake_case ): __magic_name__ = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a __magic_name__ = sum(1 for x in frequency[1:limit] if x == 1_0 ) return count if __name__ == "__main__": print(f"""{solution() = }""")
545
0
"""simple docstring""" from math import factorial def A__ ( UpperCamelCase = 100 ): return sum(int(UpperCamelCase ) for x in str(factorial(UpperCamelCase ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
700
"""simple docstring""" import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _UpperCAmelCase ( lowercase_ ): UpperCamelCase = 42 UpperCamelCase = jnp.floataa UpperCamelCase = True def lowerCamelCase ( self :Optional[int] ): super().setup() A = nn.Dense(5 , dtype=self.dtype ) def __call__( self :Tuple , *__UpperCamelCase :str , **__UpperCamelCase :List[Any] ): A = super().__call__(*__UpperCamelCase , **__UpperCamelCase ) A = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class _UpperCAmelCase ( lowercase_ ): UpperCamelCase = FlaxBigBirdForNaturalQuestionsModule def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): def cross_entropy(UpperCamelCase , UpperCamelCase , UpperCamelCase=None ): A = logits.shape[-1] A = (labels[..., None] == jnp.arange(UpperCamelCase )[None]).astype("f4" ) A = jax.nn.log_softmax(UpperCamelCase , axis=-1 ) A = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: A = reduction(UpperCamelCase ) return loss A = partial(UpperCamelCase , reduction=jnp.mean ) A = cross_entropy(UpperCamelCase , UpperCamelCase ) A = cross_entropy(UpperCamelCase , UpperCamelCase ) A = cross_entropy(UpperCamelCase , UpperCamelCase ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _UpperCAmelCase : UpperCamelCase = "google/bigbird-roberta-base" UpperCamelCase = 3_0_0_0 UpperCamelCase = 1_0_5_0_0 UpperCamelCase = 1_2_8 UpperCamelCase = 3 UpperCamelCase = 1 UpperCamelCase = 5 # tx_args UpperCamelCase = 3e-5 UpperCamelCase = 0.0 UpperCamelCase = 2_0_0_0_0 UpperCamelCase = 0.0095 UpperCamelCase = "bigbird-roberta-natural-questions" UpperCamelCase = "training-expt" UpperCamelCase = "data/nq-training.jsonl" UpperCamelCase = "data/nq-validation.jsonl" def lowerCamelCase ( self :Optional[Any] ): os.makedirs(self.base_dir , exist_ok=__UpperCamelCase ) A = os.path.join(self.base_dir , self.save_dir ) A = self.batch_size_per_device * jax.device_count() @dataclass class _UpperCAmelCase : UpperCamelCase = 42 UpperCamelCase = 4_0_9_6 # no dynamic padding on TPUs def __call__( self :List[Any] , __UpperCamelCase :Union[str, Any] ): A = self.collate_fn(__UpperCamelCase ) A = jax.tree_util.tree_map(__UpperCamelCase , __UpperCamelCase ) return batch def lowerCamelCase ( self :Tuple , __UpperCamelCase :Tuple ): A, A = self.fetch_inputs(features["input_ids"] ) A = { "input_ids": jnp.array(__UpperCamelCase , dtype=jnp.intaa ), "attention_mask": jnp.array(__UpperCamelCase , dtype=jnp.intaa ), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa ), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa ), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa ), } return batch def lowerCamelCase ( self :int , __UpperCamelCase :list ): A = [self._fetch_inputs(__UpperCamelCase ) for ids in input_ids] return zip(*__UpperCamelCase ) def lowerCamelCase ( self :Union[str, Any] , __UpperCamelCase :list ): A = [1 for _ in range(len(__UpperCamelCase ) )] while len(__UpperCamelCase ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase=None ): if seed is not None: A = dataset.shuffle(seed=UpperCamelCase ) for i in range(len(UpperCamelCase ) // batch_size ): A = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase ) @partial(jax.pmap , axis_name="batch" ) def A__ ( UpperCamelCase , UpperCamelCase , **UpperCamelCase ): def loss_fn(UpperCamelCase ): A = model_inputs.pop("start_labels" ) A = model_inputs.pop("end_labels" ) A = model_inputs.pop("pooled_labels" ) A = state.apply_fn(**UpperCamelCase , params=UpperCamelCase , dropout_rng=UpperCamelCase , train=UpperCamelCase ) A, A, A = outputs return state.loss_fn( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) A, A = jax.random.split(UpperCamelCase ) A = jax.value_and_grad(UpperCamelCase ) A, A = grad_fn(state.params ) A = jax.lax.pmean({"loss": loss} , axis_name="batch" ) A = jax.lax.pmean(UpperCamelCase , "batch" ) A = state.apply_gradients(grads=UpperCamelCase ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def A__ ( UpperCamelCase , **UpperCamelCase ): A = model_inputs.pop("start_labels" ) A = model_inputs.pop("end_labels" ) A = model_inputs.pop("pooled_labels" ) A = state.apply_fn(**UpperCamelCase , params=state.params , train=UpperCamelCase ) A, A, A = outputs A = state.loss_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) A = jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _UpperCAmelCase ( train_state.TrainState ): UpperCamelCase = struct.field(pytree_node=lowercase_ ) @dataclass class _UpperCAmelCase : UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = None def lowerCamelCase ( self :List[Any] , __UpperCamelCase :Optional[int] , __UpperCamelCase :List[str] , __UpperCamelCase :Any , __UpperCamelCase :int=None ): A = model.params A = TrainState.create( apply_fn=model.__call__ , params=__UpperCamelCase , tx=__UpperCamelCase , loss_fn=__UpperCamelCase , ) if ckpt_dir is not None: A, A, A, A, A = restore_checkpoint(__UpperCamelCase , __UpperCamelCase ) A = { "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } A, A = build_tx(**__UpperCamelCase ) A = train_state.TrainState( step=__UpperCamelCase , apply_fn=model.__call__ , params=__UpperCamelCase , tx=__UpperCamelCase , opt_state=__UpperCamelCase , ) A = args A = data_collator A = lr A = params A = jax_utils.replicate(__UpperCamelCase ) return state def lowerCamelCase ( self :List[str] , __UpperCamelCase :List[Any] , __UpperCamelCase :List[Any] , __UpperCamelCase :Optional[int] ): A = self.args A = len(__UpperCamelCase ) // args.batch_size A = jax.random.PRNGKey(0 ) A = jax.random.split(__UpperCamelCase , jax.device_count() ) for epoch in range(args.max_epochs ): A = jnp.array(0 , dtype=jnp.floataa ) A = get_batched_dataset(__UpperCamelCase , args.batch_size , seed=__UpperCamelCase ) A = 0 for batch in tqdm(__UpperCamelCase , total=__UpperCamelCase , desc=f"Running EPOCH-{epoch}" ): A = self.data_collator(__UpperCamelCase ) A, A, A = self.train_step_fn(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) running_loss += jax_utils.unreplicate(metrics["loss"] ) i += 1 if i % args.logging_steps == 0: A = jax_utils.unreplicate(state.step ) A = running_loss.item() / i A = self.scheduler_fn(state_step - 1 ) A = self.evaluate(__UpperCamelCase , __UpperCamelCase ) A = { "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(__UpperCamelCase ) ) self.logger.log(__UpperCamelCase , commit=__UpperCamelCase ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f"-e{epoch}-s{i}" , state=__UpperCamelCase ) def lowerCamelCase ( self :int , __UpperCamelCase :Optional[Any] , __UpperCamelCase :List[Any] ): A = get_batched_dataset(__UpperCamelCase , self.args.batch_size ) A = len(__UpperCamelCase ) // self.args.batch_size A = jnp.array(0 , dtype=jnp.floataa ) A = 0 for batch in tqdm(__UpperCamelCase , total=__UpperCamelCase , desc="Evaluating ... " ): A = self.data_collator(__UpperCamelCase ) A = self.val_step_fn(__UpperCamelCase , **__UpperCamelCase ) running_loss += jax_utils.unreplicate(metrics["loss"] ) i += 1 return running_loss / i def lowerCamelCase ( self :List[str] , __UpperCamelCase :List[str] , __UpperCamelCase :Optional[int] ): A = jax_utils.unreplicate(__UpperCamelCase ) print(f"SAVING CHECKPOINT IN {save_dir}" , end=" ... " ) self.model_save_fn(__UpperCamelCase , params=state.params ) with open(os.path.join(__UpperCamelCase , "opt_state.msgpack" ) , "wb" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__UpperCamelCase , "args.joblib" ) ) joblib.dump(self.data_collator , os.path.join(__UpperCamelCase , "data_collator.joblib" ) ) with open(os.path.join(__UpperCamelCase , "training_state.json" ) , "w" ) as f: json.dump({"step": state.step.item()} , __UpperCamelCase ) print("DONE" ) def A__ ( UpperCamelCase , UpperCamelCase ): print(F"RESTORING CHECKPOINT FROM {save_dir}" , end=" ... " ) with open(os.path.join(UpperCamelCase , "flax_model.msgpack" ) , "rb" ) as f: A = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase , "opt_state.msgpack" ) , "rb" ) as f: A = from_bytes(state.opt_state , f.read() ) A = joblib.load(os.path.join(UpperCamelCase , "args.joblib" ) ) A = joblib.load(os.path.join(UpperCamelCase , "data_collator.joblib" ) ) with open(os.path.join(UpperCamelCase , "training_state.json" ) , "r" ) as f: A = json.load(UpperCamelCase ) A = training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): A = num_train_steps - warmup_steps A = optax.linear_schedule(init_value=UpperCamelCase , end_value=UpperCamelCase , transition_steps=UpperCamelCase ) A = optax.linear_schedule(init_value=UpperCamelCase , end_value=1E-7 , transition_steps=UpperCamelCase ) A = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): def weight_decay_mask(UpperCamelCase ): A = traverse_util.flatten_dict(UpperCamelCase ) A = {k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase ) A = scheduler_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) A = optax.adamw(learning_rate=UpperCamelCase , weight_decay=UpperCamelCase , mask=UpperCamelCase ) return tx, lr
524
0
"""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 UpperCAmelCase_ ( unittest.TestCase ): def _lowerCamelCase ( self ) -> str: __lowercase : Dict = tempfile.mkdtemp() __lowercase : Optional[Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] __lowercase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __lowercase : str = { '''do_resize''': True, '''size''': {'''height''': 2_24, '''width''': 2_24}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], '''image_std''': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], '''do_convert_rgb''': True, } __lowercase : Union[str, Any] = os.path.join(self.tmpdirname , UpperCamelCase_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(UpperCamelCase_ , UpperCamelCase_ ) def _lowerCamelCase ( self , **UpperCamelCase_ ) -> List[str]: return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def _lowerCamelCase ( self , **UpperCamelCase_ ) -> List[Any]: return BertTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def _lowerCamelCase ( self , **UpperCamelCase_ ) -> str: return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def _lowerCamelCase ( self ) -> int: shutil.rmtree(self.tmpdirname ) def _lowerCamelCase ( self ) -> Optional[Any]: __lowercase : Tuple = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowercase : Dict = [Image.fromarray(np.moveaxis(UpperCamelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _lowerCamelCase ( self ) -> str: __lowercase : Tuple = self.get_tokenizer() __lowercase : int = self.get_rust_tokenizer() __lowercase : Union[str, Any] = self.get_image_processor() __lowercase : List[Any] = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) processor_slow.save_pretrained(self.tmpdirname ) __lowercase : int = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCamelCase_ ) __lowercase : Tuple = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) processor_fast.save_pretrained(self.tmpdirname ) __lowercase : List[Any] = 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 , UpperCamelCase_ ) self.assertIsInstance(processor_fast.tokenizer , UpperCamelCase_ ) 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 , UpperCamelCase_ ) self.assertIsInstance(processor_fast.image_processor , UpperCamelCase_ ) def _lowerCamelCase ( self ) -> Optional[Any]: __lowercase : Dict = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowercase : Tuple = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''' ) __lowercase : str = self.get_image_processor(do_normalize=UpperCamelCase_ ) __lowercase : Union[str, Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=UpperCamelCase_ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCamelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCamelCase_ ) def _lowerCamelCase ( self ) -> Dict: __lowercase : Dict = self.get_image_processor() __lowercase : str = self.get_tokenizer() __lowercase : Optional[int] = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __lowercase : Optional[Any] = self.prepare_image_inputs() __lowercase : Union[str, Any] = image_processor(UpperCamelCase_ , return_tensors='''np''' ) __lowercase : Dict = processor(images=UpperCamelCase_ , 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 _lowerCamelCase ( self ) -> int: __lowercase : Dict = self.get_image_processor() __lowercase : Optional[int] = self.get_tokenizer() __lowercase : List[str] = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __lowercase : Any = '''Alexandra,T-shirt的价格是15便士。''' __lowercase : Optional[int] = processor(text=UpperCamelCase_ ) __lowercase : Optional[int] = tokenizer(UpperCamelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowerCamelCase ( self ) -> List[Any]: __lowercase : str = self.get_image_processor() __lowercase : Dict = self.get_tokenizer() __lowercase : Any = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __lowercase : str = '''Alexandra,T-shirt的价格是15便士。''' __lowercase : Optional[Any] = self.prepare_image_inputs() __lowercase : str = processor(text=UpperCamelCase_ , images=UpperCamelCase_ ) 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(UpperCamelCase_ ): processor() def _lowerCamelCase ( self ) -> Any: __lowercase : int = self.get_image_processor() __lowercase : Optional[Any] = self.get_tokenizer() __lowercase : str = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __lowercase : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowercase : List[str] = processor.batch_decode(UpperCamelCase_ ) __lowercase : Optional[int] = tokenizer.batch_decode(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) def _lowerCamelCase ( self ) -> int: __lowercase : int = self.get_image_processor() __lowercase : Dict = self.get_tokenizer() __lowercase : Any = ChineseCLIPProcessor(tokenizer=UpperCamelCase_ , image_processor=UpperCamelCase_ ) __lowercase : List[str] = '''Alexandra,T-shirt的价格是15便士。''' __lowercase : Any = self.prepare_image_inputs() __lowercase : int = processor(text=UpperCamelCase_ , images=UpperCamelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
76
'''simple docstring''' def lowerCAmelCase_ ( a : int , a : int ): return 1 if input_a == input_a else 0 def lowerCAmelCase_ ( ): assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
394
0
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class __a ( _snake_case ): __SCREAMING_SNAKE_CASE : str = 'encodec' def __init__( self : Any , lowercase__ : Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , lowercase__ : Optional[int]=2_40_00 , lowercase__ : Any=1 , lowercase__ : List[Any]=False , lowercase__ : Optional[Any]=None , lowercase__ : Dict=None , lowercase__ : Any=1_28 , lowercase__ : Tuple=32 , lowercase__ : Tuple=1 , lowercase__ : List[Any]=[8, 5, 4, 2] , lowercase__ : List[str]="weight_norm" , lowercase__ : Union[str, Any]=7 , lowercase__ : Tuple=7 , lowercase__ : Union[str, Any]=3 , lowercase__ : Optional[int]=2 , lowercase__ : int=True , lowercase__ : int="reflect" , lowercase__ : str=2 , lowercase__ : int=2 , lowercase__ : Any=1.0 , lowercase__ : List[Any]=10_24 , lowercase__ : Optional[Any]=None , lowercase__ : str=True , **lowercase__ : List[str] , ) ->int: """simple docstring""" _lowercase = target_bandwidths _lowercase = sampling_rate _lowercase = audio_channels _lowercase = normalize _lowercase = chunk_length_s _lowercase = overlap _lowercase = hidden_size _lowercase = num_filters _lowercase = num_residual_layers _lowercase = upsampling_ratios _lowercase = norm_type _lowercase = kernel_size _lowercase = last_kernel_size _lowercase = residual_kernel_size _lowercase = dilation_growth_rate _lowercase = use_causal_conv _lowercase = pad_mode _lowercase = compress _lowercase = num_lstm_layers _lowercase = trim_right_ratio _lowercase = codebook_size _lowercase = codebook_dim if codebook_dim is not None else hidden_size _lowercase = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""") super().__init__(**lowercase__) @property def _UpperCAmelCase ( self : Optional[Any]) ->Optional[int]: """simple docstring""" if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate) @property def _UpperCAmelCase ( self : int) ->Optional[int]: """simple docstring""" if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length)) @property def _UpperCAmelCase ( self : Dict) ->int: """simple docstring""" _lowercase = np.prod(self.upsampling_ratios) return math.ceil(self.sampling_rate / hop_length) @property def _UpperCAmelCase ( self : List[Any]) ->int: """simple docstring""" return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10))
718
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( snake_case_ ): _lowercase = int(snake_case_ ) if n_element < 1: _lowercase = ValueError("""a should be a positive number""" ) raise my_error _lowercase = [1] _lowercase , _lowercase , _lowercase = (0, 0, 0) _lowercase = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _lowerCamelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _lowerCamelCase = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
572
0
"""simple docstring""" from __future__ import annotations def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> Optional[int]: '''simple docstring''' lowercase_ = 0.00 lowercase_ = 0 for resistor in resistors: if resistor <= 0: lowercase_ = F'''Resistor at index {index} has a negative or zero value!''' raise ValueError(snake_case_ ) first_sum += 1 / float(snake_case_ ) index += 1 return 1 / first_sum def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> int: '''simple docstring''' lowercase_ = 0.00 lowercase_ = 0 for resistor in resistors: sum_r += resistor if resistor < 0: lowercase_ = F'''Resistor at index {index} has a negative value!''' raise ValueError(snake_case_ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
567
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "" a_ = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a_ = None # compression type in fsspec. ex: "gzip" a_ = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : Tuple , __A : str = "" , __A : Optional[str] = None , __A : Optional[dict] = None , **__A : Optional[int] ): super().__init__(self , **__A ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode snake_case__ : Any = fsspec.open( __A , mode="rb" , protocol=__A , compression=self.compression , client_kwargs={ "requote_redirect_url": False, # see https://github.com/huggingface/datasets/pull/5459 "trust_env": True, # Enable reading proxy env variables. **(target_options or {}).pop("client_kwargs" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) snake_case__ : Dict = os.path.basename(self.file.path.split("::" )[0] ) snake_case__ : Tuple = ( self.compressed_name[: self.compressed_name.rindex("." )] if "." in self.compressed_name else self.compressed_name ) snake_case__ : Union[str, Any] = None @classmethod def _lowercase ( cls : Union[str, Any] , __A : Optional[int] ): # compressed file paths are always relative to the archive root return super()._strip_protocol(__A ).lstrip("/" ) def _lowercase ( self : Dict ): if self.dir_cache is None: snake_case__ : int = {**self.file.fs.info(self.file.path ), "name": self.uncompressed_name} snake_case__ : Optional[Any] = {f["name"]: f} def _lowercase ( self : Union[str, Any] , __A : str ): return self.file.open().read() def _lowercase ( self : str , __A : str , __A : str = "rb" , __A : str=None , __A : Tuple=True , __A : Optional[Any]=None , **__A : Optional[int] , ): snake_case__ : Optional[Any] = self._strip_protocol(__A ) if mode != "rb": raise ValueError(f'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "bz2" a_ = "bz2" a_ = ".bz2" class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "gzip" a_ = "gzip" a_ = ".gz" class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "lz4" a_ = "lz4" a_ = ".lz4" class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "xz" a_ = "xz" a_ = ".xz" class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "zstd" a_ = "zstd" a_ = ".zst" def __init__( self : Union[str, Any] , __A : str , __A : str = "rb" , __A : Optional[str] = None , __A : Optional[dict] = None , __A : int = DEFAULT_BLOCK_SIZE , **__A : Tuple , ): super().__init__( fo=__A , mode=__A , target_protocol=__A , target_options=__A , block_size=__A , **__A , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 snake_case__ : Union[str, Any] = self.file.__enter__ class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self : Optional[int] , __A : Dict ): snake_case__ : Tuple = file_ def __enter__( self : str ): self._file.__enter__() return self def __exit__( self : List[Any] , *__A : List[Any] , **__A : Union[str, Any] ): self._file.__exit__(*__A , **__A ) def __iter__( self : List[Any] ): return iter(self._file ) def _lowercase ( self : Optional[Any] ): return next(self._file ) def __getattr__( self : Union[str, Any] , __A : Optional[int] ): return getattr(self._file , __A ) def fixed_enter(*__A : Tuple , **__A : Dict ): return WrappedFile(_enter(*__A , **__A ) ) snake_case__ : List[Any] = fixed_enter
297
0
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCAmelCase( __lowerCamelCase ): __a = int(number**0.5 ) return number == sq * sq def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a = x_den * y_den * z_den __a = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) top //= hcf bottom //= hcf return top, bottom def lowerCAmelCase( __lowerCamelCase = 35 ): __a = set() __a = 42 __a = Fraction(0 ) __a = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a = x_num * y_den + x_den * y_num __a = x_den * y_den __a = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) # n=2 __a = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a = x_den * x_den * y_den * y_den if is_sq(SCREAMING_SNAKE_CASE_ ) and is_sq(SCREAMING_SNAKE_CASE_ ): __a = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) __a = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) __a = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) # n=-1 __a = x_num * y_num __a = x_den * y_num + x_num * y_den __a = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) # n=2 __a = x_num * x_num * y_num * y_num __a = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(SCREAMING_SNAKE_CASE_ ) and is_sq(SCREAMING_SNAKE_CASE_ ): __a = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) __a = int(sqrt(SCREAMING_SNAKE_CASE_ ) ) __a = gcd(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a = add_three( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) unique_s.add(SCREAMING_SNAKE_CASE_ ) for num, den in unique_s: total += Fraction(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return total.denominator + total.numerator if __name__ == "__main__": print(F'''{solution() = }''')
700
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase_ : Optional[int] = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowerCamelCase_ : Union[str, Any] = 250_004 lowerCamelCase_ : List[str] = 250_020 @require_sentencepiece @require_tokenizers class a__ ( __snake_case , unittest.TestCase ): A__ : Optional[Any] = MBartTokenizer A__ : Optional[Any] = MBartTokenizerFast A__ : Dict = True A__ : Dict = True def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: super().setUp() # We have a SentencePiece fixture for testing __a = MBartTokenizer(UpperCAmelCase , keep_accents=UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self ) -> str: __a = MBartTokenizer(UpperCAmelCase , keep_accents=UpperCAmelCase ) __a = tokenizer.tokenize('This is a test' ) self.assertListEqual(UpperCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) __a = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __a = tokenizer.convert_tokens_to_ids(UpperCAmelCase ) self.assertListEqual( UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __a = tokenizer.convert_ids_to_tokens(UpperCAmelCase ) self.assertListEqual( UpperCAmelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __a = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __a = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase , **UpperCAmelCase ) __a = self.tokenizer_class.from_pretrained(UpperCAmelCase , **UpperCAmelCase ) __a = tempfile.mkdtemp() __a = tokenizer_r.save_pretrained(UpperCAmelCase ) __a = tokenizer_p.save_pretrained(UpperCAmelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) __a = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(UpperCAmelCase , UpperCAmelCase ) # Checks everything loads correctly in the same way __a = tokenizer_r.from_pretrained(UpperCAmelCase ) __a = tokenizer_p.from_pretrained(UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase , UpperCAmelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(UpperCAmelCase ) # Save tokenizer rust, legacy_format=True __a = tempfile.mkdtemp() __a = tokenizer_r.save_pretrained(UpperCAmelCase , legacy_format=UpperCAmelCase ) __a = tokenizer_p.save_pretrained(UpperCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(UpperCAmelCase , UpperCAmelCase ) # Checks everything loads correctly in the same way __a = tokenizer_r.from_pretrained(UpperCAmelCase ) __a = tokenizer_p.from_pretrained(UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase , UpperCAmelCase ) ) shutil.rmtree(UpperCAmelCase ) # Save tokenizer rust, legacy_format=False __a = tempfile.mkdtemp() __a = tokenizer_r.save_pretrained(UpperCAmelCase , legacy_format=UpperCAmelCase ) __a = tokenizer_p.save_pretrained(UpperCAmelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __a = tokenizer_r.from_pretrained(UpperCAmelCase ) __a = tokenizer_p.from_pretrained(UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase , UpperCAmelCase ) ) shutil.rmtree(UpperCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class a__ ( unittest.TestCase ): A__ : Optional[Any] = 'facebook/mbart-large-en-ro' A__ : Union[str, Any] = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] A__ : Tuple = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] A__ : Dict = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def __SCREAMING_SNAKE_CASE ( cls ) -> Optional[Any]: __a = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) __a = 1 return cls def __SCREAMING_SNAKE_CASE ( self ) -> str: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 2_5_0_0_2_0 ) def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: __a = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self ) -> Tuple: self.assertIn(UpperCAmelCase , self.tokenizer.all_special_ids ) __a = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] __a = self.tokenizer.decode(UpperCAmelCase , skip_special_tokens=UpperCAmelCase ) __a = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase ) self.assertEqual(UpperCAmelCase , UpperCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self ) -> List[str]: __a = ['this is gunna be a long sentence ' * 2_0] assert isinstance(src_text[0] , UpperCAmelCase ) __a = 1_0 __a = self.tokenizer(UpperCAmelCase , max_length=UpperCAmelCase , truncation=UpperCAmelCase ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , UpperCAmelCase ) self.assertEqual(len(UpperCAmelCase ) , UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [2_5_0_0_2_6, 2_5_0_0_0_1] ) def __SCREAMING_SNAKE_CASE ( self ) -> str: __a = tempfile.mkdtemp() __a = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(UpperCAmelCase ) __a = MBartTokenizer.from_pretrained(UpperCAmelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , UpperCAmelCase ) @require_torch def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: __a = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase , return_tensors='pt' ) __a = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: __a = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase , truncation=UpperCAmelCase , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __a = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(UpperCAmelCase , UpperCAmelCase ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) __a = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: __a = self.tokenizer(self.src_text , padding=UpperCAmelCase , truncation=UpperCAmelCase , max_length=3 , return_tensors='pt' ) __a = self.tokenizer( text_target=self.tgt_text , padding=UpperCAmelCase , truncation=UpperCAmelCase , max_length=1_0 , return_tensors='pt' ) __a = targets['input_ids'] __a = shift_tokens_right(UpperCAmelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: __a = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(UpperCAmelCase ) , { # A, test, EOS, en_XX 'input_ids': [[6_2, 3_0_3_4, 2, 2_5_0_0_0_4]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 2_5_0_0_0_1, } , )
246
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : Tuple = { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class lowercase ( a ): lowercase__ : Any = """convbert""" def __init__( self : Union[str, Any] , _UpperCamelCase : Union[str, Any]=30_522 , _UpperCamelCase : str=768 , _UpperCamelCase : Optional[int]=12 , _UpperCamelCase : Tuple=12 , _UpperCamelCase : Union[str, Any]=3_072 , _UpperCamelCase : Union[str, Any]="gelu" , _UpperCamelCase : List[str]=0.1 , _UpperCamelCase : Tuple=0.1 , _UpperCamelCase : Optional[Any]=512 , _UpperCamelCase : Tuple=2 , _UpperCamelCase : Dict=0.0_2 , _UpperCamelCase : Any=1e-12 , _UpperCamelCase : Tuple=1 , _UpperCamelCase : Optional[int]=0 , _UpperCamelCase : List[str]=2 , _UpperCamelCase : Union[str, Any]=768 , _UpperCamelCase : Optional[int]=2 , _UpperCamelCase : Tuple=9 , _UpperCamelCase : Optional[int]=1 , _UpperCamelCase : List[str]=None , **_UpperCamelCase : Tuple , ) -> List[Any]: '''simple docstring''' super().__init__( pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase , ) SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = embedding_size SCREAMING_SNAKE_CASE = head_ratio SCREAMING_SNAKE_CASE = conv_kernel_size SCREAMING_SNAKE_CASE = num_groups SCREAMING_SNAKE_CASE = classifier_dropout class lowercase ( a ): @property def __snake_case( self : Any ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
403
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 _lowerCamelCase : Union[str, Any] = get_tests_dir('''fixtures''') class lowercase ( unittest.TestCase ): def __snake_case( self : str ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = mock.Mock() SCREAMING_SNAKE_CASE = 500 SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = HTTPError SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_UpperCamelCase ) as mock_head: SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" ) # This check we did call the fake head request mock_head.assert_called() def __snake_case( self : List[str] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json" ) @is_staging_test class lowercase ( unittest.TestCase ): @classmethod def __snake_case( cls : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(_UpperCamelCase ) @classmethod def __snake_case( cls : Dict ) -> List[str]: '''simple docstring''' try: delete_repo(token=cls._token , repo_id="test-feature-extractor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-feature-extractor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-feature-extractor" ) except HTTPError: pass def __snake_case( self : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(_UpperCamelCase ) feature_extractor.push_to_hub("test-feature-extractor" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_UpperCamelCase , getattr(_UpperCamelCase , _UpperCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-feature-extractor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( _UpperCamelCase , repo_id="test-feature-extractor" , push_to_hub=_UpperCamelCase , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_UpperCamelCase , getattr(_UpperCamelCase , _UpperCamelCase ) ) def __snake_case( self : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(_UpperCamelCase ) feature_extractor.push_to_hub("valid_org/test-feature-extractor" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_UpperCamelCase , getattr(_UpperCamelCase , _UpperCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-feature-extractor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( _UpperCamelCase , repo_id="valid_org/test-feature-extractor-org" , push_to_hub=_UpperCamelCase , use_auth_token=self._token ) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(_UpperCamelCase , getattr(_UpperCamelCase , _UpperCamelCase ) ) def __snake_case( self : List[str] ) -> Tuple: '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() SCREAMING_SNAKE_CASE = CustomFeatureExtractor.from_pretrained(_UpperCamelCase ) feature_extractor.push_to_hub("test-dynamic-feature-extractor" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"} , ) SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( F"{USER}/test-dynamic-feature-extractor" , trust_remote_code=_UpperCamelCase ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , "CustomFeatureExtractor" )
403
1
'''simple docstring''' import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class _a ( unittest.TestCase ): """simple docstring""" @require_torch def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' lowercase_ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) lowercase_ = load_dataset("""ashraq/esc50""" ) lowercase_ = dataset["""train"""]["""audio"""][-1]["""array"""] lowercase_ = audio_classifier(lowercase_ , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(lowercase_ ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def lowerCamelCase__ ( self : Dict ): '''simple docstring''' pass @slow @require_torch def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog lowercase_ = load_dataset("""ashraq/esc50""" ) lowercase_ = dataset["""train"""]["""audio"""][-1]["""array"""] lowercase_ = audio_classifier(lowercase_ , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(lowercase_ ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) lowercase_ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(lowercase_ ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) lowercase_ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(lowercase_ ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' pass
603
'''simple docstring''' import os def A_ ( ) ->Any: with open(os.path.dirname(SCREAMING_SNAKE_CASE_ ) + """/p022_names.txt""" ) as file: lowercase_ = str(file.readlines()[0] ) lowercase_ = names.replace("""\"""" , """""" ).split(""",""" ) names.sort() lowercase_ = 0 lowercase_ = 0 for i, name in enumerate(SCREAMING_SNAKE_CASE_ ): for letter in name: name_score += ord(SCREAMING_SNAKE_CASE_ ) - 64 total_score += (i + 1) * name_score lowercase_ = 0 return total_score if __name__ == "__main__": print(solution())
603
1
'''simple docstring''' import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() _UpperCamelCase : Any = logging.get_logger(__name__) def __snake_case ( lowerCAmelCase : Optional[Any] ): __UpperCAmelCase = MobileNetVaConfig(layer_norm_eps=0.0_01 ) if "_quant" in model_name: raise ValueError('Quantized models are not supported.' ) __UpperCAmelCase = re.match(r'^mobilenet_v1_([^_]*)_([^_]*)$' , __UpperCamelCase ) if matches: __UpperCAmelCase = float(matches[1] ) __UpperCAmelCase = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __UpperCAmelCase = 1001 __UpperCAmelCase = '''imagenet-1k-id2label.json''' __UpperCAmelCase = '''huggingface/label-files''' __UpperCAmelCase = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type='dataset' ) , 'r' ) ) __UpperCAmelCase = {int(__UpperCamelCase ) + 1: v for k, v in idalabel.items()} __UpperCAmelCase = '''background''' __UpperCAmelCase = idalabel __UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def __snake_case ( ): __UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __UpperCAmelCase = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ) return im @torch.no_grad() def __snake_case ( lowerCAmelCase : Dict , lowerCAmelCase : Optional[int] , lowerCAmelCase : Tuple , lowerCAmelCase : str=False ): __UpperCAmelCase = get_mobilenet_va_config(__UpperCamelCase ) # Load 🤗 model __UpperCAmelCase = MobileNetVaForImageClassification(__UpperCamelCase ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __UpperCAmelCase = MobileNetVaImageProcessor( crop_size={'width': config.image_size, 'height': config.image_size} , size={'shortest_edge': config.image_size + 32} , ) __UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ) __UpperCAmelCase = model(**__UpperCamelCase ) __UpperCAmelCase = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": __UpperCAmelCase = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ) elif model_name == "mobilenet_v1_0.75_192": __UpperCAmelCase = torch.tensor([-3.94_40, -2.31_41, -0.33_33] ) else: __UpperCAmelCase = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , __UpperCamelCase , atol=1E-4 ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__UpperCamelCase ) if push_to_hub: print('Pushing to the hub...' ) __UpperCAmelCase = '''google/''' + model_name image_processor.push_to_hub(__UpperCamelCase ) model.push_to_hub(__UpperCamelCase ) if __name__ == "__main__": _UpperCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt 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 : Tuple = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
396
"""simple docstring""" a_ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def __UpperCAmelCase ( __UpperCamelCase ): # Make sure the supplied data is a bytes-like object if not isinstance(__UpperCamelCase , __UpperCamelCase ): __lowercase : str = f"""a bytes-like object is required, not '{data.__class__.__name__}'""" raise TypeError(__UpperCamelCase ) __lowercase : Any = ''''''.join(bin(__UpperCamelCase )[2:].zfill(8 ) for byte in data ) __lowercase : List[str] = len(__UpperCamelCase ) % 6 != 0 if padding_needed: # The padding that will be added later __lowercase : int = B'''=''' * ((6 - len(__UpperCamelCase ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(__UpperCamelCase ) % 6) else: __lowercase : Any = B'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(__UpperCamelCase ) , 6 ) ).encode() + padding ) def __UpperCAmelCase ( __UpperCamelCase ): # Make sure encoded_data is either a string or a bytes-like object if not isinstance(__UpperCamelCase , __UpperCamelCase ) and not isinstance(__UpperCamelCase , __UpperCamelCase ): __lowercase : List[str] = ( '''argument should be a bytes-like object or ASCII string, ''' f"""not '{encoded_data.__class__.__name__}'""" ) raise TypeError(__UpperCamelCase ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(__UpperCamelCase , __UpperCamelCase ): try: __lowercase : List[str] = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __lowercase : Dict = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(__UpperCamelCase ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __lowercase : Tuple = encoded_data[:-padding] __lowercase : str = ''''''.join( bin(B64_CHARSET.index(__UpperCamelCase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __lowercase : Any = ''''''.join( bin(B64_CHARSET.index(__UpperCamelCase ) )[2:].zfill(6 ) for char in encoded_data ) __lowercase : int = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(__UpperCamelCase ) , 8 ) ] return bytes(__UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
76
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) __UpperCAmelCase = { '''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: __UpperCAmelCase = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ '''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 __UpperCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
712
"""simple docstring""" import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/config.json''', # See all BART models at https://huggingface.co/models?filter=bart } class __UpperCAmelCase ( _UpperCamelCase ): __lowerCamelCase : str = "bart" __lowerCamelCase : Dict = ["past_key_values"] __lowerCamelCase : List[str] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Union[str, Any] , a_ : Union[str, Any]=5_02_65 , a_ : List[str]=10_24 , a_ : str=12 , a_ : Union[str, Any]=40_96 , a_ : Tuple=16 , a_ : List[str]=12 , a_ : int=40_96 , a_ : Tuple=16 , a_ : int=0.0 , a_ : Optional[int]=0.0 , a_ : Dict="gelu" , a_ : Optional[int]=10_24 , a_ : Tuple=0.1 , a_ : str=0.0 , a_ : str=0.0 , a_ : Optional[Any]=0.02 , a_ : Any=0.0 , a_ : int=False , a_ : Dict=True , a_ : List[Any]=3 , a_ : Tuple=1 , a_ : Optional[Any]=0 , a_ : Any=2 , a_ : List[Any]=True , a_ : Dict=2 , a_ : List[str]=2 , **a_ : Dict , ) -> Dict: '''simple docstring''' a__ : List[Any] = vocab_size a__ : Dict = max_position_embeddings a__ : Optional[Any] = d_model a__ : Optional[Any] = encoder_ffn_dim a__ : Union[str, Any] = encoder_layers a__ : Union[str, Any] = encoder_attention_heads a__ : Tuple = decoder_ffn_dim a__ : Union[str, Any] = decoder_layers a__ : Union[str, Any] = decoder_attention_heads a__ : Optional[Any] = dropout a__ : str = attention_dropout a__ : Dict = activation_dropout a__ : List[Any] = activation_function a__ : Dict = init_std a__ : Dict = encoder_layerdrop a__ : List[Any] = decoder_layerdrop a__ : List[Any] = classifier_dropout a__ : Union[str, Any] = use_cache a__ : Any = encoder_layers a__ : str = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=a_ , pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , is_encoder_decoder=a_ , decoder_start_token_id=a_ , forced_eos_token_id=a_ , **a_ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , a_ ): a__ : List[Any] = self.bos_token_id warnings.warn( F"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " "The config can simply be saved and uploaded again to be fixed." ) class __UpperCAmelCase ( _UpperCamelCase ): @property def UpperCAmelCase ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: a__ : Optional[Any] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: a__ : Optional[int] = {0: "batch"} a__ : Dict = {0: "batch", 1: "past_decoder_sequence + sequence"} else: a__ : Dict = {0: "batch", 1: "decoder_sequence"} a__ : Union[str, Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(a_ , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. a__ : int = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: a__ , a__ : Any = self.num_layers for i in range(a_ ): a__ : Tuple = {0: "batch", 2: "past_sequence + sequence"} a__ : Optional[int] = {0: "batch", 2: "past_sequence + sequence"} else: a__ : List[Any] = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def UpperCAmelCase ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: a__ : int = super().outputs else: a__ : Tuple = super(a_ , self ).outputs if self.use_past: a__ , a__ : List[str] = self.num_layers for i in range(a_ ): a__ : List[Any] = {0: "batch", 2: "past_sequence + sequence"} a__ : List[str] = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def UpperCAmelCase ( self : Dict , a_ : PreTrainedTokenizer , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' a__ : Optional[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( a_ , a_ , a_ , a_ , a_ ) # Generate decoder inputs a__ : Optional[Any] = seq_length if not self.use_past else 1 a__ : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( a_ , a_ , a_ , a_ , a_ ) a__ : Union[str, Any] = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} a__ : str = dict(**a_ , **a_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch a__ , a__ : Union[str, Any] = common_inputs["input_ids"].shape a__ : List[Any] = common_inputs["decoder_input_ids"].shape[1] a__ , a__ : Tuple = self.num_attention_heads a__ : List[Any] = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) a__ : List[str] = decoder_seq_length + 3 a__ : Tuple = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) a__ : List[Any] = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(a_ , a_ )] , dim=1 ) a__ : Tuple = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered a__ , a__ : Any = self.num_layers a__ : Dict = min(a_ , a_ ) a__ : Optional[int] = max(a_ , a_ ) - min_num_layers a__ : str = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(a_ ): common_inputs["past_key_values"].append( ( torch.zeros(a_ ), torch.zeros(a_ ), torch.zeros(a_ ), torch.zeros(a_ ), ) ) # TODO: test this. a__ : List[Any] = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(a_ , a_ ): common_inputs["past_key_values"].append((torch.zeros(a_ ), torch.zeros(a_ )) ) return common_inputs def UpperCAmelCase ( self : Optional[Any] , a_ : PreTrainedTokenizer , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' a__ : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( a_ , a_ , a_ , a_ , a_ ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch a__ , a__ : List[str] = common_inputs["input_ids"].shape # Not using the same length for past_key_values a__ : Any = seqlen + 2 a__ , a__ : Any = self.num_layers a__ , a__ : List[Any] = self.num_attention_heads a__ : Optional[int] = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) a__ : str = common_inputs["attention_mask"].dtype a__ : List[str] = torch.cat( [common_inputs["attention_mask"], torch.ones(a_ , a_ , dtype=a_ )] , dim=1 ) a__ : Optional[Any] = [ (torch.zeros(a_ ), torch.zeros(a_ )) for _ in range(a_ ) ] return common_inputs def UpperCAmelCase ( self : List[Any] , a_ : PreTrainedTokenizer , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' a__ : Any = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX a__ : Any = tokenizer.num_special_tokens_to_add(a_ ) a__ : Dict = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=a_ ) # Generate dummy inputs according to compute batch and sequence a__ : int = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size a__ : Any = dict(tokenizer(a_ , return_tensors=a_ ) ) return common_inputs def UpperCAmelCase ( self : List[Any] , a_ : PreTrainedTokenizer , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , ) -> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: a__ : List[Any] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( a_ , batch_size=a_ , seq_length=a_ , is_pair=a_ , framework=a_ ) elif self.task == "causal-lm": a__ : Optional[int] = self._generate_dummy_inputs_for_causal_lm( a_ , batch_size=a_ , seq_length=a_ , is_pair=a_ , framework=a_ ) else: a__ : int = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( a_ , batch_size=a_ , seq_length=a_ , is_pair=a_ , framework=a_ ) return common_inputs def UpperCAmelCase ( self : Optional[Any] , a_ : int , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : List[Any] ) -> str: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: a__ : int = super()._flatten_past_key_values_(a_ , a_ , a_ , a_ ) else: a__ : Union[str, Any] = super(a_ , self )._flatten_past_key_values_( a_ , a_ , a_ , a_ )
251
0
def __UpperCamelCase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): while a != 0: __a , __a : Union[str, Any] = b % a, a return b def __UpperCamelCase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): if gcd(lowerCAmelCase__ , lowerCAmelCase__ ) != 1: __a : List[str] = f"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(lowerCAmelCase__ ) __a , __a , __a : Any = 1, 0, a __a , __a , __a : str = 0, 1, m while va != 0: __a : List[str] = ua // va __a , __a , __a , __a , __a , __a : List[Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
521
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase__ : @staticmethod def lowerCAmelCase (*snake_case_ : int , **snake_case_ : List[str] ): pass @is_pipeline_test @require_vision @require_timm @require_torch class UpperCamelCase__ ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Any = MODEL_FOR_OBJECT_DETECTION_MAPPING def lowerCAmelCase (self : Tuple , snake_case_ : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Dict ): __a : Union[str, Any] = ObjectDetectionPipeline(model=snake_case_ , image_processor=snake_case_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def lowerCAmelCase (self : Tuple , snake_case_ : List[str] , snake_case_ : Any ): __a : Any = object_detector('''./tests/fixtures/tests_samples/COCO/000000039769.png''' , threshold=0.0 ) self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { '''score''': ANY(snake_case_ ), '''label''': ANY(snake_case_ ), '''box''': {'''xmin''': ANY(snake_case_ ), '''ymin''': ANY(snake_case_ ), '''xmax''': ANY(snake_case_ ), '''ymax''': ANY(snake_case_ )}, } , ) import datasets __a : List[Any] = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) __a : List[str] = [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] __a : Optional[int] = object_detector(snake_case_ , threshold=0.0 ) self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for outputs in batch_outputs: self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { '''score''': ANY(snake_case_ ), '''label''': ANY(snake_case_ ), '''box''': {'''xmin''': ANY(snake_case_ ), '''ymin''': ANY(snake_case_ ), '''xmax''': ANY(snake_case_ ), '''ymax''': ANY(snake_case_ )}, } , ) @require_tf @unittest.skip('''Object detection not implemented in TF''' ) def lowerCAmelCase (self : int ): pass @require_torch def lowerCAmelCase (self : Tuple ): __a : str = '''hf-internal-testing/tiny-detr-mobilenetsv3''' __a : int = AutoModelForObjectDetection.from_pretrained(snake_case_ ) __a : int = AutoFeatureExtractor.from_pretrained(snake_case_ ) __a : Union[str, Any] = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) __a : List[str] = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=0.0 ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_5_9, '''ymin''': 1_2_0, '''xmax''': 4_8_0, '''ymax''': 3_5_9}}, {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_5_9, '''ymin''': 1_2_0, '''xmax''': 4_8_0, '''ymax''': 3_5_9}}, ] , ) __a : Dict = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_5_9, '''ymin''': 1_2_0, '''xmax''': 4_8_0, '''ymax''': 3_5_9}}, {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_5_9, '''ymin''': 1_2_0, '''xmax''': 4_8_0, '''ymax''': 3_5_9}}, ], [ {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_5_9, '''ymin''': 1_2_0, '''xmax''': 4_8_0, '''ymax''': 3_5_9}}, {'''score''': 0.3376, '''label''': '''LABEL_0''', '''box''': {'''xmin''': 1_5_9, '''ymin''': 1_2_0, '''xmax''': 4_8_0, '''ymax''': 3_5_9}}, ], ] , ) @require_torch @slow def lowerCAmelCase (self : List[Any] ): __a : Optional[Any] = '''facebook/detr-resnet-50''' __a : int = AutoModelForObjectDetection.from_pretrained(snake_case_ ) __a : str = AutoFeatureExtractor.from_pretrained(snake_case_ ) __a : Tuple = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) __a : Union[str, Any] = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_0, '''xmax''': 1_7_5, '''ymax''': 1_1_7}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_3, '''ymin''': 7_2, '''xmax''': 3_6_8, '''ymax''': 1_8_7}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_3_9, '''ymax''': 4_7_3}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ] , ) __a : Optional[Any] = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_0, '''xmax''': 1_7_5, '''ymax''': 1_1_7}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_3, '''ymin''': 7_2, '''xmax''': 3_6_8, '''ymax''': 1_8_7}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_3_9, '''ymax''': 4_7_3}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ], [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_0, '''xmax''': 1_7_5, '''ymax''': 1_1_7}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_3, '''ymin''': 7_2, '''xmax''': 3_6_8, '''ymax''': 1_8_7}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_3_9, '''ymax''': 4_7_3}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ], ] , ) @require_torch @slow def lowerCAmelCase (self : Optional[int] ): __a : Any = '''facebook/detr-resnet-50''' __a : Optional[Any] = pipeline('''object-detection''' , model=snake_case_ ) __a : Optional[int] = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_0, '''xmax''': 1_7_5, '''ymax''': 1_1_7}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_3, '''ymin''': 7_2, '''xmax''': 3_6_8, '''ymax''': 1_8_7}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_3_9, '''ymax''': 4_7_3}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ] , ) __a : List[str] = object_detector( [ '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''http://images.cocodataset.org/val2017/000000039769.jpg''', ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_0, '''xmax''': 1_7_5, '''ymax''': 1_1_7}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_3, '''ymin''': 7_2, '''xmax''': 3_6_8, '''ymax''': 1_8_7}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_3_9, '''ymax''': 4_7_3}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ], [ {'''score''': 0.9982, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_0, '''xmax''': 1_7_5, '''ymax''': 1_1_7}}, {'''score''': 0.9960, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_3, '''ymin''': 7_2, '''xmax''': 3_6_8, '''ymax''': 1_8_7}}, {'''score''': 0.9955, '''label''': '''couch''', '''box''': {'''xmin''': 0, '''ymin''': 1, '''xmax''': 6_3_9, '''ymax''': 4_7_3}}, {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ], ] , ) @require_torch @slow def lowerCAmelCase (self : Union[str, Any] ): __a : Tuple = 0.9985 __a : Tuple = '''facebook/detr-resnet-50''' __a : int = pipeline('''object-detection''' , model=snake_case_ ) __a : Optional[Any] = object_detector('''http://images.cocodataset.org/val2017/000000039769.jpg''' , threshold=snake_case_ ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9988, '''label''': '''cat''', '''box''': {'''xmin''': 1_3, '''ymin''': 5_2, '''xmax''': 3_1_4, '''ymax''': 4_7_0}}, {'''score''': 0.9987, '''label''': '''cat''', '''box''': {'''xmin''': 3_4_5, '''ymin''': 2_3, '''xmax''': 6_4_0, '''ymax''': 3_6_8}}, ] , ) @require_torch @require_pytesseract @slow def lowerCAmelCase (self : List[str] ): __a : Optional[int] = '''Narsil/layoutlmv3-finetuned-funsd''' __a : Any = 0.9993 __a : Tuple = pipeline('''object-detection''' , model=snake_case_ , threshold=snake_case_ ) __a : Optional[Any] = object_detector( '''https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png''' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'''score''': 0.9993, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 2_9_4, '''ymin''': 2_5_4, '''xmax''': 3_4_3, '''ymax''': 2_6_4}}, {'''score''': 0.9993, '''label''': '''I-ANSWER''', '''box''': {'''xmin''': 2_9_4, '''ymin''': 2_5_4, '''xmax''': 3_4_3, '''ymax''': 2_6_4}}, ] , )
521
1
import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = fname.split(os.path.sep )[-1] return re.search(r'^(.*)_\d+\.jpg$' , SCREAMING_SNAKE_CASE__ ).groups()[0] class A_ ( __UpperCamelCase ): '''simple docstring''' def __init__( self: str , a: int , a: Union[str, Any]=None , a: Optional[Any]=None ): __lowerCamelCase : List[str] = file_names __lowerCamelCase : List[Any] = image_transform __lowerCamelCase : Tuple = label_to_id def __len__( self: Optional[int] ): return len(self.file_names ) def __getitem__( self: Dict , a: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = self.file_names[idx] __lowerCamelCase : Optional[Any] = PIL.Image.open(a ) __lowerCamelCase : Tuple = raw_image.convert('RGB' ) if self.image_transform is not None: __lowerCamelCase : Dict = self.image_transform(a ) __lowerCamelCase : Optional[int] = extract_label(a ) if self.label_to_id is not None: __lowerCamelCase : Any = self.label_to_id[label] return {"image": image, "label": label} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Initialize accelerator if args.with_tracking: __lowerCamelCase : Optional[int] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: __lowerCamelCase : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __lowerCamelCase : List[str] = config['lr'] __lowerCamelCase : List[Any] = int(config['num_epochs'] ) __lowerCamelCase : Tuple = int(config['seed'] ) __lowerCamelCase : List[Any] = int(config['batch_size'] ) __lowerCamelCase : Union[str, Any] = config['image_size'] if not isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): __lowerCamelCase : str = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , 'isdigit' ): if args.checkpointing_steps == "epoch": __lowerCamelCase : Dict = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): __lowerCamelCase : int = int(args.checkpointing_steps ) else: raise ValueError( f'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: __lowerCamelCase : Any = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: __lowerCamelCase : int = os.path.split(SCREAMING_SNAKE_CASE__ )[-1].split('.' )[0] accelerator.init_trackers(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Grab all the image filenames __lowerCamelCase : Optional[int] = [os.path.join(args.data_dir , SCREAMING_SNAKE_CASE__ ) for fname in os.listdir(args.data_dir ) if fname.endswith('.jpg' )] # Build the label correspondences __lowerCamelCase : List[str] = [extract_label(SCREAMING_SNAKE_CASE__ ) for fname in file_names] __lowerCamelCase : Tuple = list(set(SCREAMING_SNAKE_CASE__ ) ) id_to_label.sort() __lowerCamelCase : Dict = {lbl: i for i, lbl in enumerate(SCREAMING_SNAKE_CASE__ )} # Set the seed before splitting the data. np.random.seed(SCREAMING_SNAKE_CASE__ ) torch.manual_seed(SCREAMING_SNAKE_CASE__ ) torch.cuda.manual_seed_all(SCREAMING_SNAKE_CASE__ ) # Split our filenames between train and validation __lowerCamelCase : Union[str, Any] = np.random.permutation(len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : List[str] = int(0.8 * len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Union[str, Any] = random_perm[:cut] __lowerCamelCase : Dict = random_perm[cut:] # For training we use a simple RandomResizedCrop __lowerCamelCase : List[Any] = Compose([RandomResizedCrop(SCREAMING_SNAKE_CASE__ , scale=(0.5, 1.0) ), ToTensor()] ) __lowerCamelCase : List[str] = PetsDataset( [file_names[i] for i in train_split] , image_transform=SCREAMING_SNAKE_CASE__ , label_to_id=SCREAMING_SNAKE_CASE__ ) # For evaluation, we use a deterministic Resize __lowerCamelCase : Optional[int] = Compose([Resize(SCREAMING_SNAKE_CASE__ ), ToTensor()] ) __lowerCamelCase : List[str] = PetsDataset([file_names[i] for i in eval_split] , image_transform=SCREAMING_SNAKE_CASE__ , label_to_id=SCREAMING_SNAKE_CASE__ ) # Instantiate dataloaders. __lowerCamelCase : Optional[Any] = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) __lowerCamelCase : str = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __lowerCamelCase : List[str] = create_model('resnet50d' , pretrained=SCREAMING_SNAKE_CASE__ , num_classes=len(SCREAMING_SNAKE_CASE__ ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __lowerCamelCase : Dict = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): __lowerCamelCase : Union[str, Any] = False for param in model.get_classifier().parameters(): __lowerCamelCase : Optional[Any] = True # We normalize the batches of images to be a bit faster. __lowerCamelCase : List[str] = torch.tensor(model.default_cfg['mean'] )[None, :, None, None].to(accelerator.device ) __lowerCamelCase : List[str] = torch.tensor(model.default_cfg['std'] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer __lowerCamelCase : Any = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler __lowerCamelCase : Dict = OneCycleLR(optimizer=SCREAMING_SNAKE_CASE__ , max_lr=SCREAMING_SNAKE_CASE__ , epochs=SCREAMING_SNAKE_CASE__ , steps_per_epoch=len(SCREAMING_SNAKE_CASE__ ) ) # 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. __lowerCamelCase : str = accelerator.prepare( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over __lowerCamelCase : int = 0 # We also need to keep track of the starting epoch so files are named properly __lowerCamelCase : Union[str, Any] = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(f'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) __lowerCamelCase : Optional[int] = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint __lowerCamelCase : Any = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) __lowerCamelCase : Dict = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` __lowerCamelCase : Any = os.path.splitext(SCREAMING_SNAKE_CASE__ )[0] if "epoch" in training_difference: __lowerCamelCase : int = int(training_difference.replace('epoch_' , '' ) ) + 1 __lowerCamelCase : int = None else: __lowerCamelCase : Any = int(training_difference.replace('step_' , '' ) ) __lowerCamelCase : List[Any] = resume_step // len(SCREAMING_SNAKE_CASE__ ) resume_step -= starting_epoch * len(SCREAMING_SNAKE_CASE__ ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): model.train() if args.with_tracking: __lowerCamelCase : Optional[Any] = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step __lowerCamelCase : str = accelerator.skip_first_batches(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader __lowerCamelCase : Optional[int] = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. __lowerCamelCase : str = {k: v.to(accelerator.device ) for k, v in batch.items()} __lowerCamelCase : Optional[int] = (batch['image'] - mean) / std __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = torch.nn.functional.cross_entropy(SCREAMING_SNAKE_CASE__ , batch['label'] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(SCREAMING_SNAKE_CASE__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = f'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: __lowerCamelCase : Union[str, Any] = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. __lowerCamelCase : Optional[int] = {k: v.to(accelerator.device ) for k, v in batch.items()} __lowerCamelCase : Optional[Any] = (batch['image'] - mean) / std with torch.no_grad(): __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = outputs.argmax(dim=-1 ) __lowerCamelCase : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch['label']) ) __lowerCamelCase : Optional[int] = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() __lowerCamelCase : Optional[int] = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { 'accuracy': 100 * eval_metric, 'train_loss': total_loss.item() / len(SCREAMING_SNAKE_CASE__ ), 'epoch': epoch, } , step=SCREAMING_SNAKE_CASE__ , ) if checkpointing_steps == "epoch": __lowerCamelCase : Optional[int] = f'epoch_{epoch}' if args.output_dir is not None: __lowerCamelCase : Optional[Any] = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) if args.with_tracking: accelerator.end_training() def UpperCamelCase__ ( ): __lowerCamelCase : Dict = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument('--data_dir' , required=SCREAMING_SNAKE_CASE__ , help='The data folder on disk.' ) parser.add_argument('--fp16' , action='store_true' , help='If passed, will use FP16 training.' ) parser.add_argument( '--mixed_precision' , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--checkpointing_steps' , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , help='Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.' , ) parser.add_argument( '--output_dir' , type=SCREAMING_SNAKE_CASE__ , 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=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , help='If the training should continue from a checkpoint folder.' , ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=SCREAMING_SNAKE_CASE__ , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) __lowerCamelCase : Optional[Any] = parser.parse_args() __lowerCamelCase : List[Any] = {'lr': 3e-2, 'num_epochs': 3, 'seed': 42, 'batch_size': 64, 'image_size': 224} training_function(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
710
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return getitem, k def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return setitem, k, v def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return delitem, k def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ): try: return fun(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ), None except Exception as e: return None, e lowercase_ = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) lowercase_ = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] lowercase_ = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] lowercase_ = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] lowercase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowercase_ = [ *[_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__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = HashMap(initial_block_size=4 ) __lowerCamelCase : Dict = {} for _, (fun, *args) in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase : str = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) assert my_res == py_res assert str(SCREAMING_SNAKE_CASE__ ) == str(SCREAMING_SNAKE_CASE__ ) assert set(SCREAMING_SNAKE_CASE__ ) == set(SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) assert set(my.items() ) == set(py.items() ) def UpperCamelCase__ ( ): def is_public(SCREAMING_SNAKE_CASE__ ) -> bool: return not name.startswith('_' ) __lowerCamelCase : Optional[Any] = {name for name in dir({} ) if is_public(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase : Dict = {name for name in dir(HashMap() ) if is_public(SCREAMING_SNAKE_CASE__ )} assert dict_public_names > hash_public_names
230
0
"""simple docstring""" import os from pathlib import Path def snake_case ( ) -> Tuple: from torch.utils.cpp_extension import load _snake_case = Path(lowerCAmelCase_ ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' _snake_case = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , lowerCAmelCase_ , with_cuda=lowerCAmelCase_ , extra_include_paths=[str(lowerCAmelCase_ )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
103
from math import sqrt def lowercase_ ( __snake_case : int ) -> bool: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and ( number >= 0 ), "'number' must been an int and positive" snake_case__ :List[str] = True # 0 and 1 are none primes. if number <= 1: snake_case__ :List[str] = False for divisor in range(2 , int(round(sqrt(__snake_case ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: snake_case__ :Optional[int] = False break # precondition assert isinstance(__snake_case , __snake_case ), "'status' must been from type bool" return status def lowercase_ ( __snake_case : Optional[Any] ) -> Dict: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N snake_case__ :Union[str, Any] = list(range(2 , n + 1 ) ) snake_case__ :Dict = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(__snake_case ) ): for j in range(i + 1 , len(__snake_case ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): snake_case__ :List[Any] = 0 # filters actual prime numbers. snake_case__ :Tuple = [x for x in begin_list if x != 0] # precondition assert isinstance(__snake_case , __snake_case ), "'ans' must been from type list" return ans def lowercase_ ( __snake_case : str ) -> int: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and (n > 2), "'N' must been an int and > 2" snake_case__ :List[str] = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(__snake_case ): ans.append(__snake_case ) # precondition assert isinstance(__snake_case , __snake_case ), "'ans' must been from type list" return ans def lowercase_ ( __snake_case : Union[str, Any] ) -> List[Any]: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and number >= 0, "'number' must been an int and >= 0" snake_case__ :int = [] # this list will be returns of the function. # potential prime number factors. snake_case__ :Tuple = 2 snake_case__ :Union[str, Any] = number if number == 0 or number == 1: ans.append(__snake_case ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(__snake_case ): while quotient != 1: if is_prime(__snake_case ) and (quotient % factor == 0): ans.append(__snake_case ) quotient /= factor else: factor += 1 else: ans.append(__snake_case ) # precondition assert isinstance(__snake_case , __snake_case ), "'ans' must been from type list" return ans def lowercase_ ( __snake_case : Any ) -> List[str]: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and ( number >= 0 ), "'number' bust been an int and >= 0" snake_case__ :Union[str, Any] = 0 # prime factorization of 'number' snake_case__ :List[Any] = prime_factorization(__snake_case ) snake_case__ :Any = max(__snake_case ) # precondition assert isinstance(__snake_case , __snake_case ), "'ans' must been from type int" return ans def lowercase_ ( __snake_case : Optional[int] ) -> int: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and ( number >= 0 ), "'number' bust been an int and >= 0" snake_case__ :Union[str, Any] = 0 # prime factorization of 'number' snake_case__ :Tuple = prime_factorization(__snake_case ) snake_case__ :Dict = min(__snake_case ) # precondition assert isinstance(__snake_case , __snake_case ), "'ans' must been from type int" return ans def lowercase_ ( __snake_case : Optional[int] ) -> Optional[Any]: '''simple docstring''' assert isinstance(__snake_case , __snake_case ), "'number' must been an int" assert isinstance(number % 2 == 0 , __snake_case ), "compare bust been from type bool" return number % 2 == 0 def lowercase_ ( __snake_case : Optional[int] ) -> Union[str, Any]: '''simple docstring''' assert isinstance(__snake_case , __snake_case ), "'number' must been an int" assert isinstance(number % 2 != 0 , __snake_case ), "compare bust been from type bool" return number % 2 != 0 def lowercase_ ( __snake_case : Optional[Any] ) -> str: '''simple docstring''' assert ( isinstance(__snake_case , __snake_case ) and (number > 2) and is_even(__snake_case ) ), "'number' must been an int, even and > 2" snake_case__ :Dict = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' snake_case__ :int = get_prime_numbers(__snake_case ) snake_case__ :Tuple = len(__snake_case ) # run variable for while-loops. snake_case__ :List[Any] = 0 snake_case__ :Tuple = None # exit variable. for break up the loops snake_case__ :Any = True while i < len_pn and loop: snake_case__ :List[str] = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: snake_case__ :Optional[int] = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(__snake_case , __snake_case ) and (len(__snake_case ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def lowercase_ ( __snake_case : Optional[int] , __snake_case : Tuple ) -> int: '''simple docstring''' assert ( isinstance(__snake_case , __snake_case ) and isinstance(__snake_case , __snake_case ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." snake_case__ :Optional[Any] = 0 while numbera != 0: snake_case__ :int = numbera % numbera snake_case__ :Any = numbera snake_case__ :List[Any] = rest # precondition assert isinstance(__snake_case , __snake_case ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def lowercase_ ( __snake_case : Union[str, Any] , __snake_case : List[Any] ) -> List[Any]: '''simple docstring''' assert ( isinstance(__snake_case , __snake_case ) and isinstance(__snake_case , __snake_case ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." snake_case__ :List[str] = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' snake_case__ :Tuple = prime_factorization(__snake_case ) snake_case__ :Union[str, Any] = prime_factorization(__snake_case ) elif numbera == 1 or numbera == 1: snake_case__ :Tuple = [] snake_case__ :Dict = [] snake_case__ :str = max(__snake_case , __snake_case ) snake_case__ :Union[str, Any] = 0 snake_case__ :List[Any] = 0 snake_case__ :str = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: snake_case__ :Union[str, Any] = prime_fac_a.count(__snake_case ) snake_case__ :Tuple = prime_fac_a.count(__snake_case ) for _ in range(max(__snake_case , __snake_case ) ): ans *= n else: snake_case__ :str = prime_fac_a.count(__snake_case ) for _ in range(__snake_case ): ans *= n done.append(__snake_case ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: snake_case__ :Any = prime_fac_a.count(__snake_case ) for _ in range(__snake_case ): ans *= n done.append(__snake_case ) # precondition assert isinstance(__snake_case , __snake_case ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def lowercase_ ( __snake_case : Optional[Any] ) -> int: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and (n >= 0), "'number' must been a positive int" snake_case__ :Tuple = 0 snake_case__ :List[Any] = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(__snake_case ): ans += 1 # precondition assert isinstance(__snake_case , __snake_case ) and is_prime( __snake_case ), "'ans' must been a prime number and from type int" return ans def lowercase_ ( __snake_case : Tuple , __snake_case : Optional[Any] ) -> List[Any]: '''simple docstring''' assert ( is_prime(__snake_case ) and is_prime(__snake_case ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" snake_case__ :Any = p_number_a + 1 # jump to the next number snake_case__ :List[Any] = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(__snake_case ): number += 1 while number < p_number_a: ans.append(__snake_case ) number += 1 # fetch the next prime number. while not is_prime(__snake_case ): number += 1 # precondition assert ( isinstance(__snake_case , __snake_case ) and ans[0] != p_number_a and ans[len(__snake_case ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def lowercase_ ( __snake_case : List[Any] ) -> Optional[Any]: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and (n >= 1), "'n' must been int and >= 1" snake_case__ :Optional[int] = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(__snake_case ) # precondition assert ans[0] == 1 and ans[len(__snake_case ) - 1] == n, "Error in function getDivisiors(...)" return ans def lowercase_ ( __snake_case : Tuple ) -> Tuple: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and ( number > 1 ), "'number' must been an int and >= 1" snake_case__ :List[str] = get_divisors(__snake_case ) # precondition assert ( isinstance(__snake_case , __snake_case ) and (divisors[0] == 1) and (divisors[len(__snake_case ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def lowercase_ ( __snake_case : str , __snake_case : Any ) -> str: '''simple docstring''' assert ( isinstance(__snake_case , __snake_case ) and isinstance(__snake_case , __snake_case ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. snake_case__ :Union[str, Any] = gcd(abs(__snake_case ) , abs(__snake_case ) ) # precondition assert ( isinstance(__snake_case , __snake_case ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def lowercase_ ( __snake_case : Tuple ) -> int: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and (n >= 0), "'n' must been a int and >= 0" snake_case__ :int = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def lowercase_ ( __snake_case : List[str] ) -> int: '''simple docstring''' assert isinstance(__snake_case , __snake_case ) and (n >= 0), "'n' must been an int and >= 0" snake_case__ :Union[str, Any] = 0 snake_case__ :int = 1 snake_case__ :int = 1 # this will be return for _ in range(n - 1 ): snake_case__ :List[Any] = ans ans += fiba snake_case__ :Optional[Any] = tmp return ans
241
0
'''simple docstring''' from __future__ import annotations def __a(SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : list[str] | None = None ): _lowerCAmelCase = word_bank or [] # create a table _lowerCAmelCase = len(SCREAMING_SNAKE_CASE_ ) + 1 _lowerCAmelCase = [] for _ in range(SCREAMING_SNAKE_CASE_ ): table.append([] ) # seed value _lowerCAmelCase = [[]] # because empty string has empty combination # iterate through the indices for i in range(SCREAMING_SNAKE_CASE_ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(SCREAMING_SNAKE_CASE_ )] == word: _lowerCAmelCase = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(SCREAMING_SNAKE_CASE_ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(SCREAMING_SNAKE_CASE_ )]: combination.reverse() return table[len(SCREAMING_SNAKE_CASE_ )] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
700
'''simple docstring''' from ...configuration_utils import PretrainedConfig class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : List[str] = "bert-generation" def __init__( self , _lowerCAmelCase=50358 , _lowerCAmelCase=1024 , _lowerCAmelCase=24 , _lowerCAmelCase=16 , _lowerCAmelCase=4096 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-12 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=1 , _lowerCAmelCase="absolute" , _lowerCAmelCase=True , **_lowerCAmelCase , ) -> Tuple: super().__init__(pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase ) _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_act _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = initializer_range _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = position_embedding_type _lowerCAmelCase = use_cache
489
0
'''simple docstring''' __lowercase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def snake_case__ ( _A: dict , _A: Optional[Any] , _A: Dict ) -> list[str]: '''simple docstring''' lowerCAmelCase = set() # keep track of all the paths to be checked lowerCAmelCase = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue lowerCAmelCase = queue.pop(0 ) # get the last node from the path lowerCAmelCase = path[-1] if node not in explored: lowerCAmelCase = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: lowerCAmelCase = list(_A ) new_path.append(_A ) queue.append(_A ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_A ) # in case there's no path between the 2 nodes return [] def snake_case__ ( _A: dict , _A: List[str] , _A: List[str] ) -> int: '''simple docstring''' if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 lowerCAmelCase = [start] lowerCAmelCase = set(_A ) # Keep tab on distances from `start` node. lowerCAmelCase = {start: 0, target: -1} while queue: lowerCAmelCase = queue.pop(0 ) if node == target: lowerCAmelCase = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_A ) queue.append(_A ) lowerCAmelCase = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
370
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __lowercase = { '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''' } def snake_case__ ( _A: str = "dhaka" , _A: int = 5 ) -> int: '''simple docstring''' lowerCAmelCase = min(_A , 50 ) # Prevent abuse! lowerCAmelCase = { """q""": query, """tbm""": """isch""", """hl""": """en""", """ijn""": """0""", } lowerCAmelCase = requests.get("""https://www.google.com/search""" , params=_A , headers=_A ) lowerCAmelCase = BeautifulSoup(html.text , """html.parser""" ) lowerCAmelCase = """""".join( re.findall(r"""AF_initDataCallback\(([^<]+)\);""" , str(soup.select("""script""" ) ) ) ) lowerCAmelCase = json.dumps(_A ) lowerCAmelCase = json.loads(_A ) lowerCAmelCase = re.findall( r"""\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",""" , _A , ) if not matched_google_image_data: return 0 lowerCAmelCase = re.sub( r"""\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]""" , """""" , str(_A ) , ) lowerCAmelCase = re.findall( r"""(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]""" , _A , ) for index, fixed_full_res_image in enumerate(_A ): if index >= max_images: return index lowerCAmelCase = bytes(_A , """ascii""" ).decode( """unicode-escape""" ) lowerCAmelCase = bytes(_A , """ascii""" ).decode( """unicode-escape""" ) lowerCAmelCase = urllib.request.build_opener() lowerCAmelCase = [ ( """User-Agent""", """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""", ) ] urllib.request.install_opener(_A ) lowerCAmelCase = f"query_{query.replace(' ' , '_' )}" if not os.path.exists(_A ): os.makedirs(_A ) urllib.request.urlretrieve( # noqa: S310 _A , f"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: __lowercase = download_images_from_google_query(sys.argv[1]) print(f'{image_count} images were downloaded to disk.') except IndexError: print('''Please provide a search term.''') raise
370
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, ) lowerCAmelCase_ : List[Any] = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Optional[int] = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Union[str, Any] = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Any = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Union[str, Any] = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys lowerCAmelCase_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
378
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( a_ ): _A : Optional[int] = ['image_processor', 'tokenizer'] _A : Optional[Any] = 'ViTImageProcessor' _A : Tuple = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self , snake_case__=None , snake_case__=None , **snake_case__ ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , snake_case__ , ) UpperCAmelCase = kwargs.pop("""feature_extractor""" ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(snake_case__ , snake_case__ ) def __call__( self , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__=None , **snake_case__ ) -> List[str]: """simple docstring""" if text is None and visual_prompt is None and images is None: raise ValueError("""You have to specify either text, visual prompt or images.""" ) if text is not None and visual_prompt is not None: raise ValueError("""You have to specify exactly one type of prompt. Either text or visual prompt.""" ) if text is not None: UpperCAmelCase = self.tokenizer(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if visual_prompt is not None: UpperCAmelCase = self.image_processor(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if images is not None: UpperCAmelCase = self.image_processor(snake_case__ , return_tensors=snake_case__ , **snake_case__ ) if visual_prompt is not None and images is not None: UpperCAmelCase = { """pixel_values""": image_features.pixel_values, """conditional_pixel_values""": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: UpperCAmelCase = { """conditional_pixel_values""": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**snake_case__ ) , tensor_type=snake_case__ ) def UpperCamelCase_ ( self , *snake_case__ , **snake_case__ ) -> Tuple: """simple docstring""" return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def UpperCamelCase_ ( self , *snake_case__ , **snake_case__ ) -> Optional[int]: """simple docstring""" return self.tokenizer.decode(*snake_case__ , **snake_case__ ) @property def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , snake_case__ , ) return self.image_processor_class @property def UpperCamelCase_ ( self ) -> Any: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , snake_case__ , ) return self.image_processor
378
1
'''simple docstring''' import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[Any] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } _SCREAMING_SNAKE_CASE : List[Any] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def UpperCamelCase_( snake_case : Tuple , snake_case : List[Any] , snake_case : Optional[int] , snake_case : Union[str, Any] , snake_case : Tuple ): '''simple docstring''' for attribute in key.split("." ): snake_case_ = getattr(snake_case , snake_case ) if weight_type is not None: snake_case_ = getattr(snake_case , snake_case ).shape else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value else: snake_case_ = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def UpperCamelCase_( snake_case : List[Any] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( snake_case , snake_case , snake_case , snake_case , hf_model.config.feat_extract_norm == "group" , ) snake_case_ = True else: for key, mapped_key in MAPPING.items(): snake_case_ = "unispeech_sat." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: if "layer_norm_for_extract" in name and (".".join(name.split("." )[:-1] ) != key): # special case since naming is very similar continue snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(snake_case )[0].split("." )[-2] snake_case_ = mapped_key.replace("*" , snake_case ) if "weight_g" in name: snake_case_ = "weight_g" elif "weight_v" in name: snake_case_ = "weight_v" elif "bias" in name: snake_case_ = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = "weight" else: snake_case_ = None set_recursively(snake_case , snake_case , snake_case , snake_case , snake_case ) continue if not is_used: unused_weights.append(snake_case ) logger.warning(f'Unused weights: {unused_weights}' ) def UpperCamelCase_( snake_case : str , snake_case : Tuple , snake_case : Optional[int] , snake_case : Any , snake_case : List[Any] ): '''simple docstring''' snake_case_ = full_name.split("conv_layers." )[-1] snake_case_ = name.split("." ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) snake_case_ = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(snake_case ) @torch.no_grad() def UpperCamelCase_( snake_case : str , snake_case : Tuple , snake_case : List[str]=None , snake_case : str=None , snake_case : List[str]=True ): '''simple docstring''' if config_path is not None: snake_case_ = UniSpeechSatConfig.from_pretrained(snake_case ) else: snake_case_ = UniSpeechSatConfig() snake_case_ = "" if is_finetuned: snake_case_ = UniSpeechSatForCTC(snake_case ) else: snake_case_ = UniSpeechSatForPreTraining(snake_case ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) snake_case_ = model[0].eval() recursively_load_weights(snake_case , snake_case ) hf_wavavec.save_pretrained(snake_case ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[Any] = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
400
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class _snake_case ( lowercase_ ): lowerCAmelCase_ : torch.FloatTensor class _snake_case ( nn.Module ): def __init__( self , a__=3 , a__=3 , a__=("DownEncoderBlock2D",) , a__=(64,) , a__=2 , a__=32 , a__="silu" , a__=True , ) -> Union[str, Any]: '''simple docstring''' super().__init__() snake_case_ = layers_per_block snake_case_ = torch.nn.Convad( a__ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case_ = None snake_case_ = nn.ModuleList([] ) # down snake_case_ = block_out_channels[0] for i, down_block_type in enumerate(a__ ): snake_case_ = output_channel snake_case_ = block_out_channels[i] snake_case_ = i == len(a__ ) - 1 snake_case_ = get_down_block( a__ , num_layers=self.layers_per_block , in_channels=a__ , out_channels=a__ , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=a__ , resnet_groups=a__ , attention_head_dim=a__ , temb_channels=a__ , ) self.down_blocks.append(a__ ) # mid snake_case_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=a__ , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=a__ , temb_channels=a__ , ) # out snake_case_ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=a__ , eps=1e-6 ) snake_case_ = nn.SiLU() snake_case_ = 2 * out_channels if double_z else out_channels snake_case_ = nn.Convad(block_out_channels[-1] , a__ , 3 , padding=1 ) snake_case_ = False def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' snake_case_ = x snake_case_ = self.conv_in(a__ ) if self.training and self.gradient_checkpointing: def create_custom_forward(a__ ): def custom_forward(*a__ ): return module(*a__ ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(a__ ) , a__ , use_reentrant=a__ ) # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , a__ , use_reentrant=a__ ) else: for down_block in self.down_blocks: snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(a__ ) , a__ ) # middle snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , a__ ) else: # down for down_block in self.down_blocks: snake_case_ = down_block(a__ ) # middle snake_case_ = self.mid_block(a__ ) # post-process snake_case_ = self.conv_norm_out(a__ ) snake_case_ = self.conv_act(a__ ) snake_case_ = self.conv_out(a__ ) return sample class _snake_case ( nn.Module ): def __init__( self , a__=3 , a__=3 , a__=("UpDecoderBlock2D",) , a__=(64,) , a__=2 , a__=32 , a__="silu" , a__="group" , ) -> int: '''simple docstring''' super().__init__() snake_case_ = layers_per_block snake_case_ = nn.Convad( a__ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case_ = None snake_case_ = nn.ModuleList([] ) snake_case_ = in_channels if norm_type == "spatial" else None # mid snake_case_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=a__ , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=a__ , temb_channels=a__ , ) # up snake_case_ = list(reversed(a__ ) ) snake_case_ = reversed_block_out_channels[0] for i, up_block_type in enumerate(a__ ): snake_case_ = output_channel snake_case_ = reversed_block_out_channels[i] snake_case_ = i == len(a__ ) - 1 snake_case_ = get_up_block( a__ , num_layers=self.layers_per_block + 1 , in_channels=a__ , out_channels=a__ , prev_output_channel=a__ , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=a__ , resnet_groups=a__ , attention_head_dim=a__ , temb_channels=a__ , resnet_time_scale_shift=a__ , ) self.up_blocks.append(a__ ) snake_case_ = output_channel # out if norm_type == "spatial": snake_case_ = SpatialNorm(block_out_channels[0] , a__ ) else: snake_case_ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=a__ , eps=1e-6 ) snake_case_ = nn.SiLU() snake_case_ = nn.Convad(block_out_channels[0] , a__ , 3 , padding=1 ) snake_case_ = False def lowerCAmelCase__ ( self , a__ , a__=None ) -> Union[str, Any]: '''simple docstring''' snake_case_ = z snake_case_ = self.conv_in(a__ ) snake_case_ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(a__ ): def custom_forward(*a__ ): return module(*a__ ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , a__ , a__ , use_reentrant=a__ ) snake_case_ = sample.to(a__ ) # up for up_block in self.up_blocks: snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(a__ ) , a__ , a__ , use_reentrant=a__ ) else: # middle snake_case_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , a__ , a__ ) snake_case_ = sample.to(a__ ) # up for up_block in self.up_blocks: snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(a__ ) , a__ , a__ ) else: # middle snake_case_ = self.mid_block(a__ , a__ ) snake_case_ = sample.to(a__ ) # up for up_block in self.up_blocks: snake_case_ = up_block(a__ , a__ ) # post-process if latent_embeds is None: snake_case_ = self.conv_norm_out(a__ ) else: snake_case_ = self.conv_norm_out(a__ , a__ ) snake_case_ = self.conv_act(a__ ) snake_case_ = self.conv_out(a__ ) return sample class _snake_case ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__=None , a__="random" , a__=False , a__=True ) -> Optional[Any]: '''simple docstring''' super().__init__() snake_case_ = n_e snake_case_ = vq_embed_dim snake_case_ = beta snake_case_ = legacy snake_case_ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case_ = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) snake_case_ = self.used.shape[0] snake_case_ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case_ = self.re_embed snake_case_ = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: snake_case_ = n_e snake_case_ = sane_index_shape def lowerCAmelCase__ ( self , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = inds.shape assert len(a__ ) > 1 snake_case_ = inds.reshape(ishape[0] , -1 ) snake_case_ = self.used.to(a__ ) snake_case_ = (inds[:, :, None] == used[None, None, ...]).long() snake_case_ = match.argmax(-1 ) snake_case_ = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case_ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case_ = self.unknown_index return new.reshape(a__ ) def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = inds.shape assert len(a__ ) > 1 snake_case_ = inds.reshape(ishape[0] , -1 ) snake_case_ = self.used.to(a__ ) if self.re_embed > self.used.shape[0]: # extra token snake_case_ = 0 # simply set to zero snake_case_ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , a__ ) return back.reshape(a__ ) def lowerCAmelCase__ ( self , a__ ) -> str: '''simple docstring''' snake_case_ = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case_ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case_ = torch.argmin(torch.cdist(a__ , self.embedding.weight ) , dim=1 ) snake_case_ = self.embedding(a__ ).view(z.shape ) snake_case_ = None snake_case_ = None # compute loss for embedding if not self.legacy: snake_case_ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case_ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case_ = z + (z_q - z).detach() # reshape back to match original input shape snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case_ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case_ = self.remap_to_used(a__ ) snake_case_ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case_ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]: '''simple docstring''' if self.remap is not None: snake_case_ = indices.reshape(shape[0] , -1 ) # add batch axis snake_case_ = self.unmap_to_all(a__ ) snake_case_ = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case_ = self.embedding(a__ ) if shape is not None: snake_case_ = z_q.view(a__ ) # reshape back to match original input shape snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class _snake_case ( lowercase_ ): def __init__( self , a__ , a__=False ) -> Optional[int]: '''simple docstring''' snake_case_ = parameters snake_case_ , snake_case_ = torch.chunk(a__ , 2 , dim=1 ) snake_case_ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) snake_case_ = deterministic snake_case_ = torch.exp(0.5 * self.logvar ) snake_case_ = torch.exp(self.logvar ) if self.deterministic: snake_case_ = snake_case_ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def lowerCAmelCase__ ( self , a__ = None ) -> torch.FloatTensor: '''simple docstring''' snake_case_ = randn_tensor( self.mean.shape , generator=a__ , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case_ = self.mean + self.std * sample return x def lowerCAmelCase__ ( self , a__=None ) -> List[str]: '''simple docstring''' if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def lowerCAmelCase__ ( self , a__ , a__=[1, 2, 3] ) -> Optional[int]: '''simple docstring''' if self.deterministic: return torch.Tensor([0.0] ) snake_case_ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return self.mean
400
1
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowercase_ ( _lowerCamelCase: Optional[int] , _lowerCamelCase: List[str] , _lowerCamelCase: Dict ) -> Any: '''simple docstring''' if isinstance(_lowerCamelCase , torch.Tensor ): return image elif isinstance(_lowerCamelCase , PIL.Image.Image ): __lowerCamelCase : Tuple = [image] if isinstance(image[0] , PIL.Image.Image ): __lowerCamelCase : Dict = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] __lowerCamelCase : Dict = np.concatenate(_lowerCamelCase , axis=0 ) __lowerCamelCase : List[Any] = np.array(_lowerCamelCase ).astype(np.floataa ) / 255.0 __lowerCamelCase : int = image.transpose(0 , 3 , 1 , 2 ) __lowerCamelCase : Any = 2.0 * image - 1.0 __lowerCamelCase : Optional[Any] = torch.from_numpy(_lowerCamelCase ) elif isinstance(image[0] , torch.Tensor ): __lowerCamelCase : Optional[int] = torch.cat(_lowerCamelCase , dim=0 ) return image def lowercase_ ( _lowerCamelCase: Any , _lowerCamelCase: Tuple , _lowerCamelCase: Dict , _lowerCamelCase: List[str]=0.9995 ) -> List[Any]: '''simple docstring''' if not isinstance(_lowerCamelCase , np.ndarray ): __lowerCamelCase : Optional[Any] = True __lowerCamelCase : Optional[Any] = va.device __lowerCamelCase : str = va.cpu().numpy() __lowerCamelCase : Dict = va.cpu().numpy() __lowerCamelCase : Optional[int] = np.sum(va * va / (np.linalg.norm(_lowerCamelCase ) * np.linalg.norm(_lowerCamelCase )) ) if np.abs(_lowerCamelCase ) > DOT_THRESHOLD: __lowerCamelCase : Union[str, Any] = (1 - t) * va + t * va else: __lowerCamelCase : List[str] = np.arccos(_lowerCamelCase ) __lowerCamelCase : Optional[Any] = np.sin(_lowerCamelCase ) __lowerCamelCase : List[Any] = theta_a * t __lowerCamelCase : Dict = np.sin(_lowerCamelCase ) __lowerCamelCase : Union[str, Any] = np.sin(theta_a - theta_t ) / sin_theta_a __lowerCamelCase : List[str] = sin_theta_t / sin_theta_a __lowerCamelCase : int = sa * va + sa * va if inputs_are_torch: __lowerCamelCase : List[Any] = torch.from_numpy(_lowerCamelCase ).to(_lowerCamelCase ) return va def lowercase_ ( _lowerCamelCase: Tuple , _lowerCamelCase: List[Any] ) -> int: '''simple docstring''' __lowerCamelCase : Any = F.normalize(_lowerCamelCase , dim=-1 ) __lowerCamelCase : str = F.normalize(_lowerCamelCase , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowercase_ ( _lowerCamelCase: Any , _lowerCamelCase: List[str] ) -> Optional[int]: '''simple docstring''' for param in model.parameters(): __lowerCamelCase : List[Any] = value class _snake_case ( a__ ): def __init__( self : Optional[Any] , UpperCAmelCase : AutoencoderKL , UpperCAmelCase : CLIPTextModel , UpperCAmelCase : CLIPModel , UpperCAmelCase : CLIPTokenizer , UpperCAmelCase : UNetaDConditionModel , UpperCAmelCase : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , UpperCAmelCase : CLIPFeatureExtractor , UpperCAmelCase : Optional[Any]=None , UpperCAmelCase : List[str]=None , UpperCAmelCase : int=None , ): super().__init__() self.register_modules( vae=UpperCAmelCase , text_encoder=UpperCAmelCase , clip_model=UpperCAmelCase , tokenizer=UpperCAmelCase , unet=UpperCAmelCase , scheduler=UpperCAmelCase , feature_extractor=UpperCAmelCase , coca_model=UpperCAmelCase , coca_tokenizer=UpperCAmelCase , coca_transform=UpperCAmelCase , ) __lowerCamelCase : List[str] = ( feature_extractor.size if isinstance(feature_extractor.size , UpperCAmelCase ) else feature_extractor.size["shortest_edge"] ) __lowerCamelCase : Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , UpperCAmelCase ) set_requires_grad(self.clip_model , UpperCAmelCase ) def lowerCamelCase__ ( self : List[Any] , UpperCAmelCase : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __lowerCamelCase : List[Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(UpperCAmelCase ) def lowerCamelCase__ ( self : List[Any] ): self.enable_attention_slicing(UpperCAmelCase ) def lowerCamelCase__ ( self : str ): set_requires_grad(self.vae , UpperCAmelCase ) def lowerCamelCase__ ( self : str ): set_requires_grad(self.vae , UpperCAmelCase ) def lowerCamelCase__ ( self : List[Any] ): set_requires_grad(self.unet , UpperCAmelCase ) def lowerCamelCase__ ( self : int ): set_requires_grad(self.unet , UpperCAmelCase ) def lowerCamelCase__ ( self : List[str] , UpperCAmelCase : Dict , UpperCAmelCase : str , UpperCAmelCase : Any ): # get the original timestep using init_timestep __lowerCamelCase : str = min(int(num_inference_steps * strength ) , UpperCAmelCase ) __lowerCamelCase : Optional[int] = max(num_inference_steps - init_timestep , 0 ) __lowerCamelCase : List[str] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : Dict , UpperCAmelCase : Any=None ): if not isinstance(UpperCAmelCase , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(UpperCAmelCase )}""" ) __lowerCamelCase : Tuple = image.to(device=UpperCAmelCase , dtype=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ): __lowerCamelCase : List[Any] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(UpperCAmelCase ) ] __lowerCamelCase : int = torch.cat(UpperCAmelCase , dim=0 ) else: __lowerCamelCase : int = self.vae.encode(UpperCAmelCase ).latent_dist.sample(UpperCAmelCase ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase : Any = 0.1_8_2_1_5 * init_latents __lowerCamelCase : List[Any] = init_latents.repeat_interleave(UpperCAmelCase , dim=0 ) __lowerCamelCase : Union[str, Any] = randn_tensor(init_latents.shape , generator=UpperCAmelCase , device=UpperCAmelCase , dtype=UpperCAmelCase ) # get latents __lowerCamelCase : List[str] = self.scheduler.add_noise(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) __lowerCamelCase : Any = init_latents return latents def lowerCamelCase__ ( self : str , UpperCAmelCase : Tuple ): __lowerCamelCase : List[Any] = self.coca_transform(UpperCAmelCase ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __lowerCamelCase : str = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __lowerCamelCase : Optional[int] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("<end_of_text>" )[0].replace("<start_of_text>" , "" ).rstrip(" .," ) def lowerCamelCase__ ( self : List[Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Union[str, Any] ): __lowerCamelCase : str = self.feature_extractor.preprocess(UpperCAmelCase ) __lowerCamelCase : int = torch.from_numpy(clip_image_input["pixel_values"][0] ).unsqueeze(0 ).to(self.device ).half() __lowerCamelCase : Optional[int] = self.clip_model.get_image_features(UpperCAmelCase ) __lowerCamelCase : Any = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=UpperCAmelCase ) __lowerCamelCase : Optional[Any] = image_embeddings_clip.repeat_interleave(UpperCAmelCase , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowerCamelCase__ ( self : Optional[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Any , ): __lowerCamelCase : List[Any] = latents.detach().requires_grad_() __lowerCamelCase : int = self.scheduler.scale_model_input(UpperCAmelCase , UpperCAmelCase ) # predict the noise residual __lowerCamelCase : Any = self.unet(UpperCAmelCase , UpperCAmelCase , encoder_hidden_states=UpperCAmelCase ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __lowerCamelCase : int = self.scheduler.alphas_cumprod[timestep] __lowerCamelCase : Optional[Any] = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase : Optional[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __lowerCamelCase : Union[str, Any] = torch.sqrt(UpperCAmelCase ) __lowerCamelCase : Tuple = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , UpperCAmelCase ): __lowerCamelCase : List[Any] = self.scheduler.sigmas[index] __lowerCamelCase : Optional[Any] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase : Union[str, Any] = 1 / 0.1_8_2_1_5 * sample __lowerCamelCase : List[Any] = self.vae.decode(UpperCAmelCase ).sample __lowerCamelCase : Dict = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase : Dict = transforms.Resize(self.feature_extractor_size )(UpperCAmelCase ) __lowerCamelCase : str = self.normalize(UpperCAmelCase ).to(latents.dtype ) __lowerCamelCase : str = self.clip_model.get_image_features(UpperCAmelCase ) __lowerCamelCase : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=UpperCAmelCase ) __lowerCamelCase : Dict = spherical_dist_loss(UpperCAmelCase , UpperCAmelCase ).mean() * clip_guidance_scale __lowerCamelCase : Union[str, Any] = -torch.autograd.grad(UpperCAmelCase , UpperCAmelCase )[0] if isinstance(self.scheduler , UpperCAmelCase ): __lowerCamelCase : Any = latents.detach() + grads * (sigma**2) __lowerCamelCase : List[str] = noise_pred_original else: __lowerCamelCase : Optional[Any] = noise_pred_original - torch.sqrt(UpperCAmelCase ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Union[str, Any] , UpperCAmelCase : Union[torch.FloatTensor, PIL.Image.Image] , UpperCAmelCase : Union[torch.FloatTensor, PIL.Image.Image] , UpperCAmelCase : Optional[str] = None , UpperCAmelCase : Optional[str] = None , UpperCAmelCase : Optional[int] = 512 , UpperCAmelCase : Optional[int] = 512 , UpperCAmelCase : float = 0.6 , UpperCAmelCase : Optional[int] = 50 , UpperCAmelCase : Optional[float] = 7.5 , UpperCAmelCase : Optional[int] = 1 , UpperCAmelCase : float = 0.0 , UpperCAmelCase : Optional[float] = 100 , UpperCAmelCase : Optional[torch.Generator] = None , UpperCAmelCase : Optional[str] = "pil" , UpperCAmelCase : bool = True , UpperCAmelCase : float = 0.8 , UpperCAmelCase : float = 0.1 , UpperCAmelCase : float = 0.1 , ): if isinstance(UpperCAmelCase , UpperCAmelCase ) and len(UpperCAmelCase ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(UpperCAmelCase )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(UpperCAmelCase , torch.Generator ) and batch_size > 1: __lowerCamelCase : List[Any] = [generator] + [None] * (batch_size - 1) __lowerCamelCase : Optional[int] = [ ("model", self.coca_model is None), ("tokenizer", self.coca_tokenizer is None), ("transform", self.coca_transform is None), ] __lowerCamelCase : Optional[Any] = [x[0] for x in coca_is_none if x[1]] __lowerCamelCase : Tuple = ", ".join(UpperCAmelCase ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(UpperCAmelCase ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) __lowerCamelCase : str = self.get_image_description(UpperCAmelCase ) if style_prompt is None: if len(UpperCAmelCase ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) __lowerCamelCase : Optional[int] = self.get_image_description(UpperCAmelCase ) # get prompt text embeddings for content and style __lowerCamelCase : str = self.tokenizer( UpperCAmelCase , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=UpperCAmelCase , return_tensors="pt" , ) __lowerCamelCase : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __lowerCamelCase : Optional[Any] = self.tokenizer( UpperCAmelCase , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=UpperCAmelCase , return_tensors="pt" , ) __lowerCamelCase : List[Any] = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __lowerCamelCase : List[str] = slerp(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # duplicate text embeddings for each generation per prompt __lowerCamelCase : Optional[int] = text_embeddings.repeat_interleave(UpperCAmelCase , dim=0 ) # set timesteps __lowerCamelCase : Tuple = "offset" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __lowerCamelCase : Optional[int] = {} if accepts_offset: __lowerCamelCase : Any = 1 self.scheduler.set_timesteps(UpperCAmelCase , **UpperCAmelCase ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.get_timesteps(UpperCAmelCase , UpperCAmelCase , self.device ) __lowerCamelCase : Optional[int] = timesteps[:1].repeat(UpperCAmelCase ) # Preprocess image __lowerCamelCase : int = preprocess(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) __lowerCamelCase : Optional[Any] = self.prepare_latents( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , text_embeddings.dtype , self.device , UpperCAmelCase ) __lowerCamelCase : Optional[int] = preprocess(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) __lowerCamelCase : Optional[Any] = self.prepare_latents( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , text_embeddings.dtype , self.device , UpperCAmelCase ) __lowerCamelCase : Dict = slerp(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if clip_guidance_scale > 0: __lowerCamelCase : str = self.get_clip_image_embeddings(UpperCAmelCase , UpperCAmelCase ) __lowerCamelCase : Any = self.get_clip_image_embeddings(UpperCAmelCase , UpperCAmelCase ) __lowerCamelCase : str = slerp( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __lowerCamelCase : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __lowerCamelCase : Dict = content_text_input.input_ids.shape[-1] __lowerCamelCase : List[Any] = self.tokenizer([""] , padding="max_length" , max_length=UpperCAmelCase , return_tensors="pt" ) __lowerCamelCase : Optional[int] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __lowerCamelCase : str = uncond_embeddings.repeat_interleave(UpperCAmelCase , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __lowerCamelCase : str = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __lowerCamelCase : Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __lowerCamelCase : Optional[int] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __lowerCamelCase : str = torch.randn(UpperCAmelCase , generator=UpperCAmelCase , device="cpu" , dtype=UpperCAmelCase ).to( self.device ) else: __lowerCamelCase : Optional[Any] = torch.randn(UpperCAmelCase , generator=UpperCAmelCase , device=self.device , dtype=UpperCAmelCase ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) __lowerCamelCase : Dict = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __lowerCamelCase : Optional[Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __lowerCamelCase : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __lowerCamelCase : int = {} if accepts_eta: __lowerCamelCase : Union[str, Any] = eta # check if the scheduler accepts generator __lowerCamelCase : Optional[int] = "generator" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __lowerCamelCase : str = generator with self.progress_bar(total=UpperCAmelCase ): for i, t in enumerate(UpperCAmelCase ): # expand the latents if we are doing classifier free guidance __lowerCamelCase : Any = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __lowerCamelCase : Union[str, Any] = self.scheduler.scale_model_input(UpperCAmelCase , UpperCAmelCase ) # predict the noise residual __lowerCamelCase : Any = self.unet(UpperCAmelCase , UpperCAmelCase , encoder_hidden_states=UpperCAmelCase ).sample # perform classifier free guidance if do_classifier_free_guidance: __lowerCamelCase , __lowerCamelCase : Tuple = noise_pred.chunk(2 ) __lowerCamelCase : Tuple = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __lowerCamelCase : Dict = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __lowerCamelCase , __lowerCamelCase : List[Any] = self.cond_fn( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ) # compute the previous noisy sample x_t -> x_t-1 __lowerCamelCase : Any = self.scheduler.step(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __lowerCamelCase : int = 1 / 0.1_8_2_1_5 * latents __lowerCamelCase : List[Any] = self.vae.decode(UpperCAmelCase ).sample __lowerCamelCase : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowerCamelCase : int = self.numpy_to_pil(UpperCAmelCase ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=UpperCAmelCase , nsfw_content_detected=UpperCAmelCase )
366
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer __A = logging.get_logger(__name__) __A = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A = [ '''small''', '''small-base''', '''medium''', '''medium-base''', '''intermediate''', '''intermediate-base''', '''large''', '''large-base''', '''xlarge''', '''xlarge-base''', ] __A = { '''vocab_file''': { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt''', '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt''', '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt''', '''funnel-transformer/medium-base''': ( '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt''' ), '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt''', '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt''', '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt''', '''funnel-transformer/xlarge-base''': ( '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json''', '''funnel-transformer/small-base''': ( '''https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json''', '''funnel-transformer/medium-base''': ( '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json''', '''funnel-transformer/large-base''': ( '''https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json''' ), '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json''', '''funnel-transformer/xlarge-base''': ( '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json''' ), }, } __A = {F"""funnel-transformer/{name}""": 512 for name in _model_names} __A = {F"""funnel-transformer/{name}""": {'''do_lower_case''': True} for name in _model_names} class _snake_case ( a__ ): snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_INIT_CONFIGURATION snake_case__ = FunnelTokenizer snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = 2 def __init__( self : List[Any] , UpperCAmelCase : List[str]=None , UpperCAmelCase : Optional[int]=None , UpperCAmelCase : List[Any]=True , UpperCAmelCase : int="<unk>" , UpperCAmelCase : List[Any]="<sep>" , UpperCAmelCase : List[str]="<pad>" , UpperCAmelCase : Union[str, Any]="<cls>" , UpperCAmelCase : int="<mask>" , UpperCAmelCase : List[str]="<s>" , UpperCAmelCase : Union[str, Any]="</s>" , UpperCAmelCase : List[Any]=True , UpperCAmelCase : Tuple=True , UpperCAmelCase : int=None , UpperCAmelCase : int="##" , **UpperCAmelCase : Dict , ): super().__init__( UpperCAmelCase , tokenizer_file=UpperCAmelCase , do_lower_case=UpperCAmelCase , unk_token=UpperCAmelCase , sep_token=UpperCAmelCase , pad_token=UpperCAmelCase , cls_token=UpperCAmelCase , mask_token=UpperCAmelCase , bos_token=UpperCAmelCase , eos_token=UpperCAmelCase , clean_text=UpperCAmelCase , tokenize_chinese_chars=UpperCAmelCase , strip_accents=UpperCAmelCase , wordpieces_prefix=UpperCAmelCase , **UpperCAmelCase , ) __lowerCamelCase : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , UpperCAmelCase ) != do_lower_case or normalizer_state.get("strip_accents" , UpperCAmelCase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase ) != tokenize_chinese_chars ): __lowerCamelCase : Tuple = getattr(UpperCAmelCase , normalizer_state.pop("type" ) ) __lowerCamelCase : Optional[int] = do_lower_case __lowerCamelCase : Union[str, Any] = strip_accents __lowerCamelCase : Optional[Any] = tokenize_chinese_chars __lowerCamelCase : Optional[Any] = normalizer_class(**UpperCAmelCase ) __lowerCamelCase : List[Any] = do_lower_case def lowerCamelCase__ ( self : Union[str, Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Tuple=None ): __lowerCamelCase : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase__ ( self : Dict , UpperCAmelCase : List[int] , UpperCAmelCase : Optional[List[int]] = None ): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase__ ( self : Tuple , UpperCAmelCase : str , UpperCAmelCase : Optional[str] = None ): __lowerCamelCase : List[Any] = self._tokenizer.model.save(UpperCAmelCase , name=UpperCAmelCase ) return tuple(UpperCAmelCase )
366
1
from __future__ import annotations import typing from collections import Counter def lowerCamelCase_ ( __UpperCamelCase ): A_ = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__UpperCamelCase , max_perimeter + 1 ): A_ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__UpperCamelCase ): A_ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCamelCase_ ( __UpperCamelCase = 10_00 ): A_ = pythagorean_triple(__UpperCamelCase ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
141
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # 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(__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 lowerCamelCase_ ( __UpperCamelCase ): config.addinivalue_line( '''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' ) config.addinivalue_line( '''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' ) config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' ) config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' ) config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' ) config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' ) def lowerCamelCase_ ( __UpperCamelCase ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(__UpperCamelCase ) def lowerCamelCase_ ( __UpperCamelCase ): from transformers.testing_utils import pytest_terminal_summary_main A_ = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__UpperCamelCase , id=__UpperCamelCase ) def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase ): # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: A_ = 0 # Doctest custom flag to ignore output. SCREAMING_SNAKE_CASE : Dict = doctest.register_optionflag("IGNORE_RESULT") SCREAMING_SNAKE_CASE : Optional[int] = doctest.OutputChecker class __lowercase ( A ): def lowerCAmelCase_ ( self , a__ , a__ , a__ ) -> List[str]: '''simple docstring''' if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , a__ , a__ , a__ ) SCREAMING_SNAKE_CASE : List[str] = CustomOutputChecker SCREAMING_SNAKE_CASE : Optional[int] = HfDoctestModule SCREAMING_SNAKE_CASE : Any = HfDocTestParser
141
1
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor snake_case_ : List[Any] = logging.get_logger(__name__) class A__ ( _UpperCamelCase ): def __init__( self : Optional[int] , *_a : Any , **_a : int ) -> Optional[int]: """simple docstring""" warnings.warn( '''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use MobileViTImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
715
import string import numpy def lowerCamelCase( a__ ,a__): return b if a == 0 else greatest_common_divisor(b % a ,a__) class A__ : UpperCAmelCase = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) UpperCAmelCase = numpy.vectorize(lambda UpperCamelCase__ : x % 36 ) UpperCAmelCase = numpy.vectorize(UpperCamelCase__ ) def __init__( self : int , _a : numpy.ndarray ) -> None: """simple docstring""" _SCREAMING_SNAKE_CASE =self.modulus(_a ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key _SCREAMING_SNAKE_CASE =encrypt_key.shape[0] def __UpperCamelCase ( self : Dict , _a : str ) -> int: """simple docstring""" return self.key_string.index(_a ) def __UpperCamelCase ( self : List[str] , _a : int ) -> str: """simple docstring""" return self.key_string[round(_a )] def __UpperCamelCase ( self : int ) -> None: """simple docstring""" _SCREAMING_SNAKE_CASE =round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: _SCREAMING_SNAKE_CASE =det % len(self.key_string ) _SCREAMING_SNAKE_CASE =len(self.key_string ) if greatest_common_divisor(_a , len(self.key_string ) ) != 1: _SCREAMING_SNAKE_CASE =( f"determinant modular {req_l} of encryption key({det}) " f"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(_a ) def __UpperCamelCase ( self : List[str] , _a : str ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =[char for char in text.upper() if char in self.key_string] _SCREAMING_SNAKE_CASE =chars[-1] while len(_a ) % self.break_key != 0: chars.append(_a ) return "".join(_a ) def __UpperCamelCase ( self : List[str] , _a : str ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =self.process_text(text.upper() ) _SCREAMING_SNAKE_CASE ='''''' for i in range(0 , len(_a ) - self.break_key + 1 , self.break_key ): _SCREAMING_SNAKE_CASE =text[i : i + self.break_key] _SCREAMING_SNAKE_CASE =[self.replace_letters(_a ) for char in batch] _SCREAMING_SNAKE_CASE =numpy.array([vec] ).T _SCREAMING_SNAKE_CASE =self.modulus(self.encrypt_key.dot(_a ) ).T.tolist()[ 0 ] _SCREAMING_SNAKE_CASE =''''''.join( self.replace_digits(_a ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def __UpperCamelCase ( self : Union[str, Any] ) -> numpy.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: _SCREAMING_SNAKE_CASE =det % len(self.key_string ) _SCREAMING_SNAKE_CASE =None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: _SCREAMING_SNAKE_CASE =i break _SCREAMING_SNAKE_CASE =( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(_a ) ) def __UpperCamelCase ( self : str , _a : str ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =self.make_decrypt_key() _SCREAMING_SNAKE_CASE =self.process_text(text.upper() ) _SCREAMING_SNAKE_CASE ='''''' for i in range(0 , len(_a ) - self.break_key + 1 , self.break_key ): _SCREAMING_SNAKE_CASE =text[i : i + self.break_key] _SCREAMING_SNAKE_CASE =[self.replace_letters(_a ) for char in batch] _SCREAMING_SNAKE_CASE =numpy.array([vec] ).T _SCREAMING_SNAKE_CASE =self.modulus(decrypt_key.dot(_a ) ).T.tolist()[0] _SCREAMING_SNAKE_CASE =''''''.join( self.replace_digits(_a ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def lowerCamelCase( ): _SCREAMING_SNAKE_CASE =int(input('''Enter the order of the encryption key: ''')) _SCREAMING_SNAKE_CASE =[] print('''Enter each row of the encryption key with space separated integers''') for _ in range(a__): _SCREAMING_SNAKE_CASE =[int(a__) for x in input().split()] hill_matrix.append(a__) _SCREAMING_SNAKE_CASE =HillCipher(numpy.array(a__)) print('''Would you like to encrypt or decrypt some text? (1 or 2)''') _SCREAMING_SNAKE_CASE =input('''\n1. Encrypt\n2. Decrypt\n''') if option == "1": _SCREAMING_SNAKE_CASE =input('''What text would you like to encrypt?: ''') print('''Your encrypted text is:''') print(hc.encrypt(a__)) elif option == "2": _SCREAMING_SNAKE_CASE =input('''What text would you like to decrypt?: ''') print('''Your decrypted text is:''') print(hc.decrypt(a__)) if __name__ == "__main__": import doctest doctest.testmod() main()
191
0
'''simple docstring''' import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class A ( _a ): def __lowerCAmelCase ( self : Any ) -> Optional[int]: """simple docstring""" _a = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: """simple docstring""" with self.assertRaises(__a ): _a = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def __lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" with self.assertRaises(__a ): _a = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''bool''' ) , type=Value('''int64''' ) ) ) def __lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" _a = pa.array(TypedSequence([1, 2, 3] , type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowerCAmelCase ( self : List[str] ) -> int: """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _a = pa.array(TypedSequence(['''foo''', '''bar'''] , type=Value('''int64''' ) ) ) def __lowerCAmelCase ( self : str ) -> int: """simple docstring""" _a = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowerCAmelCase ( self : Tuple ) -> Tuple: """simple docstring""" _a = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=Value('''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) def __lowerCAmelCase ( self : Any ) -> Any: """simple docstring""" _a = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def __lowerCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _a = pa.array(TypedSequence(['''foo''', '''bar'''] , type=ArrayaD((1, 3) , '''int64''' ) ) ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" _a = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def __lowerCAmelCase ( self : Dict ) -> Tuple: """simple docstring""" _a = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def __lowerCAmelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" import PIL.Image _a = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( '''datasets.arrow_writer.cast_to_python_objects''' , side_effect=__a ) as mock_cast_to_python_objects: _a = pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image] , type=Image() ) ) _a , _a = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('''optimize_list_casting''' , __a ) self.assertFalse(kwargs['''optimize_list_casting'''] ) def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Any ): '''simple docstring''' _a = pa.BufferReader(__snake_case ) if isinstance(__snake_case , pa.Buffer ) else pa.memory_map(__snake_case ) _a = pa.ipc.open_stream(__snake_case ) _a = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ (UpperCamelCase : Dict , UpperCamelCase : Any ): '''simple docstring''' _a = pa.BufferOutputStream() _a = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case , schema=__snake_case , writer_batch_size=__snake_case ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case_ (): '''simple docstring''' _a = pa.BufferOutputStream() _a = Features({'''labels''': ClassLabel(names=['''neg''', '''pos'''] )} ) with ArrowWriter(stream=__snake_case , features=__snake_case ) as writer: writer.write({'''labels''': 0} ) writer.write({'''labels''': 1} ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _a = pa.BufferReader(output.getvalue() ) _a = pa.ipc.open_stream(__snake_case ) _a = f.read_all() _a = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__snake_case ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) def snake_case_ (UpperCamelCase : Dict ): '''simple docstring''' _a = pa.BufferOutputStream() with ArrowWriter( stream=__snake_case , writer_batch_size=__snake_case , hash_salt='''split_name''' , check_duplicates=__snake_case , ) as writer: with pytest.raises(__snake_case ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=[1, 2] ) _a , _a = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def snake_case_ (UpperCamelCase : int ): '''simple docstring''' _a = pa.BufferOutputStream() with ArrowWriter( stream=__snake_case , writer_batch_size=__snake_case , hash_salt='''split_name''' , check_duplicates=__snake_case , ) as writer: with pytest.raises(__snake_case ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=10 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=10 ) _a , _a = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def snake_case_ (UpperCamelCase : List[Any] ): '''simple docstring''' _a = pa.BufferOutputStream() with ArrowWriter( stream=__snake_case , writer_batch_size=__snake_case , hash_salt='''split_name''' , check_duplicates=__snake_case , ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=1 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=2 ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ (UpperCamelCase : int , UpperCamelCase : Dict ): '''simple docstring''' _a = pa.BufferOutputStream() _a = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case , schema=__snake_case , writer_batch_size=__snake_case ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) writer.write_batch({'''col_1''': [], '''col_2''': []} ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ (UpperCamelCase : Tuple , UpperCamelCase : str ): '''simple docstring''' _a = pa.BufferOutputStream() _a = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case , schema=__snake_case , writer_batch_size=__snake_case ) as writer: writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : int ): '''simple docstring''' _a = pa.BufferOutputStream() _a = pa.schema(__snake_case ) if fields else None with ArrowWriter(stream=__snake_case , schema=__snake_case , writer_batch_size=__snake_case ) as writer: writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]} ) ) writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]} ) ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__snake_case , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case_ (): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} _a = os.path.join(__snake_case , '''test.arrow''' ) with ArrowWriter(path=__snake_case , schema=pa.schema(__snake_case ) ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__snake_case , metadata=writer._schema.metadata ) _check_output(__snake_case , 1 ) def snake_case_ (UpperCamelCase : List[str] ): '''simple docstring''' if pa.types.is_list(__snake_case ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case_ (UpperCamelCase : List[str] , UpperCamelCase : Tuple ): '''simple docstring''' if isinstance(lst[0] , __snake_case ): change_first_primitive_element_in_list(lst[0] , __snake_case ) else: _a = value @pytest.mark.parametrize('''optimized_int_type, expected_dtype''' , [(None, pa.intaa()), (Value('''int32''' ), pa.intaa())] ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : List[Any] ): '''simple docstring''' _a = pa.array(TypedSequence(__snake_case , optimized_int_type=__snake_case ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( '''col, expected_dtype''' , [ ('''attention_mask''', pa.inta()), ('''special_tokens_mask''', pa.inta()), ('''token_type_ids''', pa.inta()), ('''input_ids''', pa.intaa()), ('''other''', pa.intaa()), ] , ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case_ (UpperCamelCase : int , UpperCamelCase : str , UpperCamelCase : Tuple ): '''simple docstring''' _a = pa.array(OptimizedTypedSequence(__snake_case , col=__snake_case ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _a = copy.deepcopy(__snake_case ) _a = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__snake_case , __snake_case ) _a = pa.array(OptimizedTypedSequence(__snake_case , col=__snake_case ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('''raise_exception''' , [False, True] ) def snake_case_ (UpperCamelCase : Dict , UpperCamelCase : Optional[int] ): '''simple docstring''' _a = str(tmp_path / '''dataset-train.arrow''' ) try: with ArrowWriter(path=__snake_case ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case_ (UpperCamelCase : Union[str, Any] ): '''simple docstring''' _a = '''mock://dataset-train.arrow''' with ArrowWriter(path=__snake_case , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__snake_case ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__snake_case ) def snake_case_ (): '''simple docstring''' _a = pa.BufferOutputStream() with ParquetWriter(stream=__snake_case ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) _a , _a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _a = pa.BufferReader(output.getvalue() ) _a = pq.read_table(__snake_case ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('''embed_local_files''' , [False, True] ) def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : str ): '''simple docstring''' import PIL.Image _a = str(tmp_path / '''test_image_rgb.jpg''' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__snake_case , format='''png''' ) _a = pa.BufferOutputStream() with ParquetWriter( stream=__snake_case , features=Features({'''image''': Image()} ) , embed_local_files=__snake_case ) as writer: writer.write({'''image''': image_path} ) writer.finalize() _a = pa.BufferReader(output.getvalue() ) _a = pq.read_table(__snake_case ) _a = pa_table.to_pydict() if embed_local_files: assert isinstance(out['''image'''][0]['''path'''] , __snake_case ) with open(__snake_case , '''rb''' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case_ (): '''simple docstring''' _a = pa.schema([pa.field('''col_1''' , pa.string() , nullable=__snake_case )] ) _a = pa.BufferOutputStream() with ArrowWriter(stream=__snake_case ) as writer: writer._build_writer(inferred_schema=__snake_case ) assert writer._schema == pa.schema([pa.field('''col_1''' , pa.string() )] )
22
"""simple docstring""" import fire from utils import calculate_rouge, save_json def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=None, **__snake_case ) -> Optional[int]: """simple docstring""" _UpperCamelCase = [x.strip() for x in open(__snake_case ).readlines()] _UpperCamelCase = [x.strip() for x in open(__snake_case ).readlines()][: len(__snake_case )] _UpperCamelCase = calculate_rouge(__snake_case, __snake_case, **__snake_case ) if save_path is not None: save_json(__snake_case, __snake_case, indent=__snake_case ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
19
0
def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : bool = False ): '''simple docstring''' if not isinstance(lowercase , lowercase ): lowerCamelCase_ = f"""Expected string as input, found {type(lowercase )}""" raise ValueError(lowercase ) if not isinstance(lowercase , lowercase ): lowerCamelCase_ = f"""Expected boolean as use_pascal parameter, found {type(lowercase )}""" raise ValueError(lowercase ) lowerCamelCase_ = input_str.split('_' ) lowerCamelCase_ = 0 if use_pascal else 1 lowerCamelCase_ = words[start_index:] lowerCamelCase_ = [word[0].upper() + word[1:] for word in words_to_capitalize] lowerCamelCase_ = '' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
651
from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase : List[Any] = logging.get_logger(__name__) class A( UpperCamelCase ): '''simple docstring''' UpperCamelCase = ['''pixel_values'''] def __init__( self : List[Any] , A_ : bool = True , A_ : Dict[str, int] = None , A_ : PILImageResampling = PILImageResampling.BICUBIC , A_ : bool = True , A_ : Dict[str, int] = None , A_ : bool = True , A_ : Union[int, float] = 1 / 255 , A_ : bool = True , A_ : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN , A_ : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD , **A_ : Tuple , ) -> None: """simple docstring""" super().__init__(**A_ ) lowerCamelCase_ = size if size is not None else {'shortest_edge': 224} lowerCamelCase_ = get_size_dict(A_ , default_to_square=A_ ) lowerCamelCase_ = crop_size if crop_size is not None else {'height': 224, 'width': 224} lowerCamelCase_ = get_size_dict(A_ , param_name='crop_size' ) lowerCamelCase_ = do_resize lowerCamelCase_ = size lowerCamelCase_ = resample lowerCamelCase_ = do_center_crop lowerCamelCase_ = crop_size lowerCamelCase_ = do_rescale lowerCamelCase_ = rescale_factor lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase_ = image_std if image_std is not None else IMAGENET_DEFAULT_STD def a__ ( self : Optional[Any] , A_ : np.ndarray , A_ : Dict[str, int] , A_ : PILImageResampling = PILImageResampling.BICUBIC , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Tuple , ) -> np.ndarray: """simple docstring""" lowerCamelCase_ = get_size_dict(A_ , default_to_square=A_ ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowerCamelCase_ = int((256 / 224) * size['shortest_edge'] ) lowerCamelCase_ = get_resize_output_image_size(A_ , size=A_ , default_to_square=A_ ) lowerCamelCase_ = {'height': output_size[0], 'width': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}""" ) return resize( A_ , size=(size_dict['height'], size_dict['width']) , resample=A_ , data_format=A_ , **A_ ) def a__ ( self : Any , A_ : np.ndarray , A_ : Dict[str, int] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Any , ) -> np.ndarray: """simple docstring""" lowerCamelCase_ = get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f"""Size dict must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def a__ ( self : Optional[Any] , A_ : np.ndarray , A_ : Union[int, float] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : Optional[int] , ) -> np.ndarray: """simple docstring""" return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def a__ ( self : List[str] , A_ : np.ndarray , A_ : Union[float, List[float]] , A_ : Union[float, List[float]] , A_ : Optional[Union[str, ChannelDimension]] = None , **A_ : str , ) -> np.ndarray: """simple docstring""" return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def a__ ( self : Optional[int] , A_ : ImageInput , A_ : Optional[bool] = None , A_ : Optional[Dict[str, int]] = None , A_ : PILImageResampling = None , A_ : Optional[bool] = None , A_ : Optional[Dict[str, int]] = None , A_ : Optional[bool] = None , A_ : Optional[float] = None , A_ : Optional[bool] = None , A_ : Optional[Union[float, Iterable[float]]] = None , A_ : Optional[Union[float, Iterable[float]]] = None , A_ : Optional[TensorType] = None , A_ : ChannelDimension = ChannelDimension.FIRST , **A_ : List[Any] , ) -> BatchFeature: """simple docstring""" lowerCamelCase_ = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ = resample if resample is not None else self.resample lowerCamelCase_ = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ = image_mean if image_mean is not None else self.image_mean lowerCamelCase_ = image_std if image_std is not None else self.image_std lowerCamelCase_ = size if size is not None else self.size lowerCamelCase_ = get_size_dict(A_ , default_to_square=A_ ) lowerCamelCase_ = crop_size if crop_size is not None else self.crop_size lowerCamelCase_ = get_size_dict(A_ , param_name='crop_size' ) lowerCamelCase_ = make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. lowerCamelCase_ = [to_numpy_array(A_ ) for image in images] if do_resize: lowerCamelCase_ = [self.resize(A_ , A_ , A_ ) for image in images] if do_center_crop: lowerCamelCase_ = [self.center_crop(A_ , A_ ) for image in images] if do_rescale: lowerCamelCase_ = [self.rescale(A_ , A_ ) for image in images] if do_normalize: lowerCamelCase_ = [self.normalize(A_ , A_ , A_ ) for image in images] lowerCamelCase_ = [to_channel_dimension_format(A_ , A_ ) for image in images] lowerCamelCase_ = {'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
651
1
'''simple docstring''' import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient UpperCAmelCase_ = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' UpperCAmelCase__ = test_results.split(""" """ ) UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. UpperCAmelCase__ = expressions[-2] if """=""" in expressions[-1] else expressions[-1] for i, expression in enumerate(SCREAMING_SNAKE_CASE__ ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' UpperCAmelCase__ = {} UpperCAmelCase__ = None UpperCAmelCase__ = False for line in failures_short_lines.split("""\n""" ): if re.search(r"""_ \[doctest\]""" , SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = True UpperCAmelCase__ = line.split(""" """ )[2] elif in_error and not line.split(""" """ )[0].isdigit(): UpperCAmelCase__ = line UpperCAmelCase__ = False return failures class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[int] , _UpperCAmelCase : str , _UpperCAmelCase : Dict ): """simple docstring""" UpperCAmelCase__ = title UpperCAmelCase__ = doc_test_results["""time_spent"""].split(""",""" )[0] UpperCAmelCase__ = doc_test_results["""success"""] UpperCAmelCase__ = doc_test_results["""failures"""] UpperCAmelCase__ = self.n_success + self.n_failures # Failures and success of the modeling tests UpperCAmelCase__ = doc_test_results @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = [self._time_spent] UpperCAmelCase__ = 0 for time in time_spent: UpperCAmelCase__ = time.split(""":""" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(_UpperCAmelCase ) == 1: UpperCAmelCase__ = [0, 0, time_parts[0]] UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'''{int(_UpperCAmelCase )}h{int(_UpperCAmelCase )}m{int(_UpperCAmelCase )}s''' @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" return { "type": "section", "text": { "type": "plain_text", "text": f'''🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.''', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } @property def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" return { "type": "section", "text": { "type": "plain_text", "text": ( f'''There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in''' f''' {self.time}.''' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" UpperCAmelCase__ = 40 UpperCAmelCase__ = {k: v["""failed"""] for k, v in doc_test_results.items() if isinstance(_UpperCAmelCase , _UpperCAmelCase )} UpperCAmelCase__ = """""" for category, failures in category_failures.items(): if len(_UpperCAmelCase ) == 0: continue if report != "": report += "\n\n" report += f'''*{category} failures*:'''.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(_UpperCAmelCase ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'''The following examples had failures:\n\n\n{report}\n''', }, } @property def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" UpperCAmelCase__ = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(_UpperCAmelCase ) @staticmethod def SCREAMING_SNAKE_CASE__ ( ): """simple docstring""" UpperCAmelCase__ = [ { """type""": """section""", """text""": { """type""": """plain_text""", """text""": """There was an issue running the tests.""", }, """accessory""": { """type""": """button""", """text""": {"""type""": """plain_text""", """text""": """Check Action results""", """emoji""": True}, """url""": f'''https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } ] print("""Sending the following payload""" ) print(json.dumps({"""blocks""": json.loads(_UpperCAmelCase )} ) ) client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , text="""There was an issue running the tests.""" , blocks=_UpperCAmelCase , ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" print("""Sending the following payload""" ) print(json.dumps({"""blocks""": json.loads(self.payload )} ) ) UpperCAmelCase__ = f'''{self.n_failures} failures out of {self.n_tests} tests,''' if self.n_failures else """All tests passed.""" UpperCAmelCase__ = client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , blocks=self.payload , text=_UpperCAmelCase , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Any , _UpperCAmelCase : List[str] ): """simple docstring""" UpperCAmelCase__ = """""" for key, value in failures.items(): UpperCAmelCase__ = value[:2_00] + """ [Truncated]""" if len(_UpperCAmelCase ) > 2_50 else value failures_text += f'''*{key}*\n_{value}_\n\n''' UpperCAmelCase__ = job_name UpperCAmelCase__ = {"""type""": """section""", """text""": {"""type""": """mrkdwn""", """text""": text}} if job_link is not None: UpperCAmelCase__ = { """type""": """button""", """text""": {"""type""": """plain_text""", """text""": """GitHub Action job""", """emoji""": True}, """url""": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" if self.thread_ts is None: raise ValueError("""Can only post reply if a post has been made.""" ) UpperCAmelCase__ = self.doc_test_results.pop("""job_link""" ) self.doc_test_results.pop("""failures""" ) self.doc_test_results.pop("""success""" ) self.doc_test_results.pop("""time_spent""" ) UpperCAmelCase__ = sorted(self.doc_test_results.items() , key=lambda _UpperCAmelCase : t[0] ) for job, job_result in sorted_dict: if len(job_result["""failures"""] ): UpperCAmelCase__ = f'''*Num failures* :{len(job_result['failed'] )} \n''' UpperCAmelCase__ = job_result["""failures"""] UpperCAmelCase__ = self.get_reply_blocks(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , text=_UpperCAmelCase ) print("""Sending the following reply""" ) print(json.dumps({"""blocks""": blocks} ) ) client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , text=f'''Results for {job}''' , blocks=_UpperCAmelCase , thread_ts=self.thread_ts["""ts"""] , ) time.sleep(1 ) def _UpperCamelCase ( ): '''simple docstring''' UpperCAmelCase__ = os.environ["""GITHUB_RUN_ID"""] UpperCAmelCase__ = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100''' UpperCAmelCase__ = requests.get(SCREAMING_SNAKE_CASE__ ).json() UpperCAmelCase__ = {} try: jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) UpperCAmelCase__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = requests.get(url + F'''&page={i + 2}''' ).json() jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return jobs except Exception as e: print("""Unknown error, could not fetch links.""" , SCREAMING_SNAKE_CASE__ ) return {} def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' UpperCAmelCase__ = {} if os.path.exists(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = os.listdir(SCREAMING_SNAKE_CASE__ ) for file in files: try: with open(os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , encoding="""utf-8""" ) as f: UpperCAmelCase__ = f.read() except UnicodeDecodeError as e: raise ValueError(F'''Could not open {os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )}.''' ) from e return _artifact def _UpperCamelCase ( ): '''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] , _UpperCAmelCase : str ): """simple docstring""" UpperCAmelCase__ = name UpperCAmelCase__ = [] def __str__( self : str ): """simple docstring""" return self.name def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , _UpperCAmelCase : str ): """simple docstring""" self.paths.append({"""name""": self.name, """path""": path} ) UpperCAmelCase__ = {} UpperCAmelCase__ = filter(os.path.isdir , os.listdir() ) for directory in directories: UpperCAmelCase__ = directory if artifact_name not in _available_artifacts: UpperCAmelCase__ = Artifact(SCREAMING_SNAKE_CASE__ ) _available_artifacts[artifact_name].add_path(SCREAMING_SNAKE_CASE__ ) return _available_artifacts if __name__ == "__main__": UpperCAmelCase_ = get_job_links() UpperCAmelCase_ = retrieve_available_artifacts() UpperCAmelCase_ = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' UpperCAmelCase_ = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job UpperCAmelCase_ = github_actions_job_links.get('run_doctests') UpperCAmelCase_ = available_artifacts['doc_tests_gpu_test_reports'].paths[0] UpperCAmelCase_ = retrieve_artifact(artifact_path['name']) if "stats" in artifact: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = handle_test_results(artifact['stats']) UpperCAmelCase_ = failed UpperCAmelCase_ = success UpperCAmelCase_ = time_spent[1:-1] + ', ' UpperCAmelCase_ = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): UpperCAmelCase_ = line.replace('FAILED ', '') UpperCAmelCase_ = line.split()[0].replace('\n', '') if "::" in line: UpperCAmelCase_ , UpperCAmelCase_ = line.split('::') else: UpperCAmelCase_ , UpperCAmelCase_ = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): UpperCAmelCase_ = docs[file_regex] doc_test_results[category]["failed"].append(test) UpperCAmelCase_ = all_failures[test] if test in all_failures else 'N/A' UpperCAmelCase_ = failure break UpperCAmelCase_ = Message('🤗 Results of the doc tests.', doc_test_results) message.post() message.post_reply()
603
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase_ ( torch.nn.Module ): '''simple docstring''' def __init__( self : Tuple , _UpperCAmelCase : List[str]="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(_UpperCAmelCase , self ).__init__() UpperCAmelCase__ = AutoModel.from_pretrained(_UpperCAmelCase , return_dict=_UpperCAmelCase ) UpperCAmelCase__ = torch.nn.CosineSimilarity(3 , 1E-08 ) UpperCAmelCase__ = torch.nn.Softmax(dim=1 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **_UpperCAmelCase : List[str] ): """simple docstring""" return self.bert(**_UpperCAmelCase ).last_hidden_state def SCREAMING_SNAKE_CASE__ ( self : Tuple , _UpperCAmelCase : List[str] ): """simple docstring""" return token_embeddings.sum(2 , keepdim=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : str , _UpperCAmelCase : Any , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : List[Any]=1 ): """simple docstring""" return self.softmax(T * self.cos(_UpperCAmelCase , _UpperCAmelCase ) ) def SCREAMING_SNAKE_CASE__ ( self : Dict , _UpperCAmelCase : Any , _UpperCAmelCase : List[str] ): """simple docstring""" UpperCAmelCase__ = W_supports["""sizes"""].tolist() UpperCAmelCase__ = W_supports["""start_token_id"""].item() UpperCAmelCase__ = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCAmelCase__ = self.BERT(**_UpperCAmelCase ) UpperCAmelCase__ = self.BERT(**_UpperCAmelCase ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = W_supports["""input_ids"""] == start_token_id UpperCAmelCase__ = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(_UpperCAmelCase ): if i == 0: UpperCAmelCase__ = 0 else: UpperCAmelCase__ = support_sizes[i - 1] UpperCAmelCase__ = S[s : s + size][start_token_masks[s : s + size]] UpperCAmelCase__ = S[s : s + size][end_token_masks[s : s + size]] UpperCAmelCase__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCAmelCase__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCAmelCase__ = torch.vstack((p_starts, p_start) ) UpperCAmelCase__ = torch.vstack((p_ends, p_end) ) else: UpperCAmelCase__ = p_start UpperCAmelCase__ = p_end return p_starts, p_ends
603
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin lowercase__ : Optional[int] = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n" class UpperCAmelCase ( unittest.TestCase , UpperCAmelCase__ ): '''simple docstring''' def snake_case__ ( self : Any ): """simple docstring""" snake_case_ = load_tool("text-question-answering" ) self.tool.setup() snake_case_ = load_tool("text-question-answering" , remote=__lowercase ) def snake_case__ ( self : str ): """simple docstring""" snake_case_ = self.tool(__lowercase , "What did Hugging Face do in April 2021?" ) self.assertEqual(__lowercase , "launched the BigScience Research Workshop" ) def snake_case__ ( self : Optional[int] ): """simple docstring""" snake_case_ = self.remote_tool(__lowercase , "What did Hugging Face do in April 2021?" ) self.assertEqual(__lowercase , "launched the BigScience Research Workshop" ) def snake_case__ ( self : int ): """simple docstring""" snake_case_ = self.tool(text=__lowercase , question="What did Hugging Face do in April 2021?" ) self.assertEqual(__lowercase , "launched the BigScience Research Workshop" ) def snake_case__ ( self : List[Any] ): """simple docstring""" snake_case_ = self.remote_tool(text=__lowercase , question="What did Hugging Face do in April 2021?" ) self.assertEqual(__lowercase , "launched the BigScience Research Workshop" )
139
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] , __lowercase : List[str] , __lowercase : Tuple , __lowercase : bool = True , __lowercase : bool = False ): """simple docstring""" snake_case_ = scheduler snake_case_ = optimizers if isinstance(__lowercase , (list, tuple) ) else [optimizers] snake_case_ = split_batches snake_case_ = step_with_optimizer snake_case_ = GradientState() def snake_case__ ( self : Dict , *__lowercase : List[str] , **__lowercase : Any ): """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*__lowercase , **__lowercase ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*__lowercase , **__lowercase ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step snake_case_ = AcceleratorState().num_processes for _ in range(__lowercase ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , "total_steps" ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*__lowercase , **__lowercase ) else: self.scheduler.step(*__lowercase , **__lowercase ) def snake_case__ ( self : Optional[Any] ): """simple docstring""" return self.scheduler.get_last_lr() def snake_case__ ( self : Optional[int] ): """simple docstring""" return self.scheduler.state_dict() def snake_case__ ( self : Union[str, Any] , __lowercase : Union[str, Any] ): """simple docstring""" self.scheduler.load_state_dict(__lowercase ) def snake_case__ ( self : int ): """simple docstring""" return self.scheduler.get_lr() def snake_case__ ( self : str , *__lowercase : int , **__lowercase : Optional[Any] ): """simple docstring""" return self.scheduler.print_lr(*__lowercase , **__lowercase )
139
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=_a ) class __lowerCamelCase (_a ): _lowercase = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) _lowercase = Features({"""audio""": Audio()} ) _lowercase = Features({"""labels""": ClassLabel} ) _lowercase = "audio" _lowercase = "labels" def snake_case_ ( self: str,A_: int ): '''simple docstring''' if self.label_column not in features: raise ValueError(F'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column],A_ ): raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' ) __UpperCamelCase = copy.deepcopy(self ) __UpperCamelCase = self.label_schema.copy() __UpperCamelCase = features[self.label_column] __UpperCamelCase = label_schema return task_template @property def snake_case_ ( self: Optional[int] ): '''simple docstring''' return { self.audio_column: "audio", self.label_column: "labels", }
1
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--txt2img_unclip''', default='''kakaobrain/karlo-v1-alpha''', type=str, required=False, help='''The pretrained txt2img unclip.''', ) __snake_case = parser.parse_args() __snake_case = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) __snake_case = CLIPImageProcessor() __snake_case = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''') __snake_case = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
1
1
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowercase = logging.get_logger(__name__) lowercase = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} lowercase = { """vocab_file""": { """allegro/herbert-base-cased""": """https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json""" }, """merges_file""": { """allegro/herbert-base-cased""": """https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt""" }, } lowercase = {"""allegro/herbert-base-cased""": 514} lowercase = {} class SCREAMING_SNAKE_CASE_ ( _lowercase): '''simple docstring''' __magic_name__ : Optional[int] = VOCAB_FILES_NAMES __magic_name__ : int = PRETRAINED_VOCAB_FILES_MAP __magic_name__ : Optional[int] = PRETRAINED_INIT_CONFIGURATION __magic_name__ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ : Union[str, Any] = HerbertTokenizer def __init__( self , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__="<s>" , lowerCamelCase__="<unk>" , lowerCamelCase__="<pad>" , lowerCamelCase__="<mask>" , lowerCamelCase__="</s>" , **lowerCamelCase__ , ) -> int: '''simple docstring''' super().__init__( lowerCamelCase__ , lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , cls_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , **lowerCamelCase__ , ) def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None) -> List[int]: '''simple docstring''' snake_case__ : str = [self.cls_token_id] snake_case__ : Optional[Any] = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = False) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase__ , token_ids_a=lowerCamelCase__ , already_has_special_tokens=lowerCamelCase__) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase__)) + [1] return [1] + ([0] * len(lowerCamelCase__)) + [1] + ([0] * len(lowerCamelCase__)) + [1] def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None) -> List[int]: '''simple docstring''' snake_case__ : Union[str, Any] = [self.sep_token_id] snake_case__ : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None) -> Tuple[str]: '''simple docstring''' snake_case__ : List[Any] = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__) return tuple(lowerCamelCase__)
150
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def A__ ( _UpperCAmelCase : int , _UpperCAmelCase : List[Any] ) -> Optional[Any]: '''simple docstring''' snake_case__ : Optional[int] = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" snake_case__ : List[Any] = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ).convert("RGB" ) snake_case__ : List[str] = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3) , (0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1) ), ] ) snake_case__ : Any = transform(_UpperCAmelCase ).unsqueeze(0 ).to(_UpperCAmelCase ) return image def A__ ( _UpperCAmelCase : Tuple ) -> Union[str, Any]: '''simple docstring''' if "visual_encoder" in key: snake_case__ : Any = re.sub("visual_encoder*" , "vision_model.encoder" , _UpperCAmelCase ) if "blocks" in key: snake_case__ : List[Any] = re.sub(r"blocks" , "layers" , _UpperCAmelCase ) if "attn" in key: snake_case__ : Optional[Any] = re.sub(r"attn" , "self_attn" , _UpperCAmelCase ) if "norm1" in key: snake_case__ : List[str] = re.sub(r"norm1" , "layer_norm1" , _UpperCAmelCase ) if "norm2" in key: snake_case__ : Union[str, Any] = re.sub(r"norm2" , "layer_norm2" , _UpperCAmelCase ) if "encoder.norm" in key: snake_case__ : List[Any] = re.sub(r"encoder.norm" , "post_layernorm" , _UpperCAmelCase ) if "encoder.patch_embed.proj" in key: snake_case__ : List[str] = re.sub(r"encoder.patch_embed.proj" , "embeddings.patch_embedding" , _UpperCAmelCase ) if "encoder.pos_embed" in key: snake_case__ : List[Any] = re.sub(r"encoder.pos_embed" , "embeddings.position_embedding" , _UpperCAmelCase ) if "encoder.cls_token" in key: snake_case__ : Optional[Any] = re.sub(r"encoder.cls_token" , "embeddings.class_embedding" , _UpperCAmelCase ) if "self_attn" in key: snake_case__ : Optional[Any] = re.sub(r"self_attn.proj" , "self_attn.projection" , _UpperCAmelCase ) return key @torch.no_grad() def A__ ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict=None ) -> int: '''simple docstring''' if config_path is not None: snake_case__ : List[Any] = BlipConfig.from_pretrained(_UpperCAmelCase ) else: snake_case__ : Optional[int] = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) snake_case__ : Tuple = BlipForConditionalGeneration(_UpperCAmelCase ).eval() snake_case__ : Optional[int] = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" snake_case__ : Optional[Any] = blip_decoder(pretrained=_UpperCAmelCase , image_size=3_84 , vit="base" ) snake_case__ : str = pt_model.eval() snake_case__ : Any = pt_model.state_dict() for key in modified_state_dict.copy(): snake_case__ : Optional[int] = modified_state_dict.pop(_UpperCAmelCase ) snake_case__ : List[Any] = rename_key(_UpperCAmelCase ) snake_case__ : List[str] = value hf_model.load_state_dict(_UpperCAmelCase ) snake_case__ : str = 3_84 snake_case__ : Dict = load_demo_image(image_size=_UpperCAmelCase , device="cpu" ) snake_case__ : int = BertTokenizer.from_pretrained("bert-base-uncased" ) snake_case__ : int = tokenizer(["a picture of"] ).input_ids snake_case__ : List[str] = hf_model.generate(_UpperCAmelCase , _UpperCAmelCase ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] snake_case__ : Tuple = hf_model.generate(_UpperCAmelCase ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_UpperCAmelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' snake_case__ : Optional[int] = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) snake_case__ : str = blip_vqa(pretrained=_UpperCAmelCase , image_size=_UpperCAmelCase , vit="base" ) vqa_model.eval() snake_case__ : Union[str, Any] = vqa_model.state_dict() for key in modified_state_dict.copy(): snake_case__ : str = modified_state_dict.pop(_UpperCAmelCase ) snake_case__ : Any = rename_key(_UpperCAmelCase ) snake_case__ : Optional[Any] = value snake_case__ : Union[str, Any] = BlipForQuestionAnswering(_UpperCAmelCase ) hf_vqa_model.load_state_dict(_UpperCAmelCase ) snake_case__ : List[Any] = ["How many dogs are in this image?"] snake_case__ : Optional[Any] = tokenizer(_UpperCAmelCase , return_tensors="pt" ).input_ids snake_case__ : List[Any] = hf_vqa_model.generate(_UpperCAmelCase , _UpperCAmelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) snake_case__ : List[str] = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" snake_case__ : Optional[int] = blip_itm(pretrained=_UpperCAmelCase , image_size=_UpperCAmelCase , vit="base" ) itm_model.eval() snake_case__ : str = itm_model.state_dict() for key in modified_state_dict.copy(): snake_case__ : Tuple = modified_state_dict.pop(_UpperCAmelCase ) snake_case__ : Optional[Any] = rename_key(_UpperCAmelCase ) snake_case__ : List[str] = value snake_case__ : Any = BlipForImageTextRetrieval(_UpperCAmelCase ) snake_case__ : Union[str, Any] = ["A picture of a woman with a dog sitting in a beach"] snake_case__ : Optional[Any] = tokenizer( _UpperCAmelCase , return_tensors="pt" , padding="max_length" , truncation=_UpperCAmelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_UpperCAmelCase ) hf_itm_model.eval() snake_case__ : List[str] = hf_itm_model(_UpperCAmelCase , _UpperCAmelCase , use_itm_head=_UpperCAmelCase ) snake_case__ : List[Any] = hf_itm_model(_UpperCAmelCase , _UpperCAmelCase , use_itm_head=_UpperCAmelCase ) assert out[0].item() == 0.2_1_1_0_6_8_7_4_9_4_2_7_7_9_5_4 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5_6_9_8_8_4_5_3_8_6_5_0_5_1_2_7 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": lowercase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowercase = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
150
1
"""simple docstring""" import colorsys from PIL import Image # type: ignore def SCREAMING_SNAKE_CASE ( snake_case, snake_case, snake_case): __snake_case = x __snake_case = y for step in range(snake_case): # noqa: B007 __snake_case = a * a - b * b + x __snake_case = 2 * a * b + y __snake_case = 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 SCREAMING_SNAKE_CASE ( snake_case): if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def SCREAMING_SNAKE_CASE ( snake_case): if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55) for i in colorsys.hsv_to_rgb(snake_case, 1, 1)) def SCREAMING_SNAKE_CASE ( snake_case = 8_00, snake_case = 6_00, snake_case = -0.6, snake_case = 0, snake_case = 3.2, snake_case = 50, snake_case = True, ): __snake_case = Image.new('''RGB''', (image_width, image_height)) __snake_case = img.load() # loop through the image-coordinates for image_x in range(snake_case): for image_y in range(snake_case): # determine the figure-coordinates based on the image-coordinates __snake_case = figure_width / image_width * image_height __snake_case = figure_center_x + (image_x / image_width - 0.5) * figure_width __snake_case = figure_center_y + (image_y / image_height - 0.5) * figure_height __snake_case = get_distance(snake_case, snake_case, snake_case) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __snake_case = get_color_coded_rgb(snake_case) else: __snake_case = get_black_and_white_rgb(snake_case) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure __lowercase : Optional[Any] = 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()
564
"""simple docstring""" import warnings 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 __lowercase : Union[str, Any] = logging.get_logger(__name__) __lowercase : List[str] = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class _A ( _UpperCAmelCase ): """simple docstring""" UpperCamelCase_ : Optional[Any] = '''segformer''' def __init__( self : Optional[Any] , A_ : Tuple=3 , A_ : int=4 , A_ : int=[2, 2, 2, 2] , A_ : Any=[8, 4, 2, 1] , A_ : str=[32, 64, 160, 256] , A_ : str=[7, 3, 3, 3] , A_ : Dict=[4, 2, 2, 2] , A_ : List[str]=[1, 2, 5, 8] , A_ : Union[str, Any]=[4, 4, 4, 4] , A_ : Union[str, Any]="gelu" , A_ : int=0.0 , A_ : Tuple=0.0 , A_ : List[str]=0.1 , A_ : Tuple=0.02 , A_ : Optional[Any]=0.1 , A_ : int=1E-6 , A_ : Optional[int]=256 , A_ : Tuple=255 , **A_ : str , ) -> str: super().__init__(**A_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( '''Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be''' ''' removed, as the behaviour will default to that of reshape_last_stage = True.''' , A_ , ) __snake_case = num_channels __snake_case = num_encoder_blocks __snake_case = depths __snake_case = sr_ratios __snake_case = hidden_sizes __snake_case = patch_sizes __snake_case = strides __snake_case = mlp_ratios __snake_case = num_attention_heads __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = classifier_dropout_prob __snake_case = initializer_range __snake_case = drop_path_rate __snake_case = layer_norm_eps __snake_case = decoder_hidden_size __snake_case = kwargs.get('''reshape_last_stage''' , A_ ) __snake_case = semantic_loss_ignore_index class _A ( _UpperCAmelCase ): """simple docstring""" UpperCamelCase_ : Optional[Any] = version.parse('''1.11''' ) @property def lowercase ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowercase ( self : List[Any] ) -> float: return 1E-4 @property def lowercase ( self : Any ) -> int: return 12
564
1
'''simple docstring''' def _UpperCAmelCase ( _UpperCamelCase : str, _UpperCamelCase : str ) -> int: if len(_UpperCamelCase ) != len(_UpperCamelCase ): raise ValueError('''String lengths must match!''' ) A_ = 0 for chara, chara in zip(_UpperCamelCase, _UpperCamelCase ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
174
'''simple docstring''' import math def _UpperCAmelCase ( _UpperCamelCase : int ) -> bool: return math.sqrt(_UpperCamelCase ) * math.sqrt(_UpperCamelCase ) == num def _UpperCAmelCase ( _UpperCamelCase : int ) -> bool: A_ = 0 A_ = n while left <= right: A_ = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: A_ = mid - 1 else: A_ = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
174
1
'''simple docstring''' from __future__ import annotations import math def lowerCAmelCase_ ( snake_case__ ): '''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(snake_case__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True lowercase : List[str] = [num for num in range(3, 10_00_01, 2) if not is_prime(num)] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' if not isinstance(snake_case__ , snake_case__ ): raise ValueError('''n must be an integer''' ) if n <= 0: raise ValueError('''n must be >= 0''' ) A : int = [] for num in range(len(snake_case__ ) ): A : Union[str, Any] = 0 while 2 * i * i <= odd_composites[num]: A : List[Any] = odd_composites[num] - 2 * i * i if is_prime(snake_case__ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(snake_case__ ) == n: return list_nums return [] def lowerCAmelCase_ ( ): '''simple docstring''' return compute_nums(1 )[0] if __name__ == "__main__": print(f'''{solution() = }''')
634
'''simple docstring''' import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=2 , ) -> Any: """simple docstring""" A : Union[str, Any] = parent A : Optional[Any] = batch_size A : Tuple = image_size A : str = patch_size A : Dict = num_channels A : Tuple = is_training A : List[Any] = use_labels A : Optional[Any] = hidden_size A : Dict = num_hidden_layers A : Union[str, Any] = num_attention_heads A : List[Any] = intermediate_size A : Any = hidden_act A : Dict = hidden_dropout_prob A : Any = attention_probs_dropout_prob A : Dict = type_sequence_label_size A : List[Any] = initializer_range A : Dict = scope A : Any = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) A : int = (image_size // patch_size) ** 2 A : Optional[Any] = num_patches + 1 def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : str = None if self.use_labels: A : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A : Dict = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Any: """simple docstring""" return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : str = ViTModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Optional[Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" A : Any = ViTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Any = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A : Optional[Any] = 1 A : str = ViTForMaskedImageModeling(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : Union[str, Any] = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" A : str = self.type_sequence_label_size A : Optional[int] = ViTForImageClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : List[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A : int = 1 A : Any = ViTForImageClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() A : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A : str = model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : int = self.prepare_config_and_inputs() ( ( A ), ( A ), ( A ), ) : int = config_and_inputs A : Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class A ( __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) __magic_name__ = ( {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification} if is_torch_available() else {} ) __magic_name__ = True __magic_name__ = False __magic_name__ = False __magic_name__ = False def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : List[str] = ViTModelTester(self ) A : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" pass def __lowerCAmelCase ( self ) -> int: """simple docstring""" A, A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Any = model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , nn.Linear ) ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A, A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Tuple = model_class(SCREAMING_SNAKE_CASE ) A : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : List[str] = [*signature.parameters.keys()] A : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) @slow def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : Optional[Any] = ViTModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None @slow def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : List[Any] = ViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' ).to(SCREAMING_SNAKE_CASE ) A : Optional[int] = self.default_image_processor A : int = prepare_img() A : Tuple = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): A : Any = model(**SCREAMING_SNAKE_CASE ) # verify the logits A : List[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) A : List[str] = torch.tensor([-0.2_744, 0.8_215, -0.0_836] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Dict = ViTModel.from_pretrained('''facebook/dino-vits8''' ).to(SCREAMING_SNAKE_CASE ) A : int = ViTImageProcessor.from_pretrained('''facebook/dino-vits8''' , size=480 ) A : Tuple = prepare_img() A : List[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) A : Tuple = inputs.pixel_values.to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): A : Any = model(SCREAMING_SNAKE_CASE , interpolate_pos_encoding=SCREAMING_SNAKE_CASE ) # verify the logits A : int = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE ) A : Union[str, Any] = torch.tensor( [[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : List[Any] = ViTModel.from_pretrained('''facebook/dino-vits8''' , torch_dtype=torch.floataa , device_map='''auto''' ) A : int = self.default_image_processor A : List[str] = prepare_img() A : Union[str, Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) A : List[Any] = inputs.pixel_values.to(SCREAMING_SNAKE_CASE ) # forward pass to make sure inference works in fp16 with torch.no_grad(): A : str = model(SCREAMING_SNAKE_CASE )
634
1
import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py __A : Dict = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. __A : int = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. __A : List[Any] = re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') __A : Dict = re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. __A : Dict = re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Fill this with tuples (pipeline_tag, model_mapping, auto_model) __A : int = [ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def __a ( A__ : Any ): SCREAMING_SNAKE_CASE = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" , __lowercase ) return [m.group(0 ) for m in matches] def __a ( ): SCREAMING_SNAKE_CASE = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE = { config.replace("Config" , "" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. SCREAMING_SNAKE_CASE = collections.defaultdict(__lowercase ) SCREAMING_SNAKE_CASE = collections.defaultdict(__lowercase ) SCREAMING_SNAKE_CASE = collections.defaultdict(__lowercase ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(__lowercase ): SCREAMING_SNAKE_CASE = None if _re_tf_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE = tf_models SCREAMING_SNAKE_CASE = _re_tf_models.match(__lowercase ).groups()[0] elif _re_flax_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE = flax_models SCREAMING_SNAKE_CASE = _re_flax_models.match(__lowercase ).groups()[0] elif _re_pt_models.match(__lowercase ) is not None: SCREAMING_SNAKE_CASE = pt_models SCREAMING_SNAKE_CASE = _re_pt_models.match(__lowercase ).groups()[0] if lookup_dict is not None: while len(__lowercase ) > 0: if attr_name in model_prefix_to_model_type: SCREAMING_SNAKE_CASE = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE = ''.join(camel_case_split(__lowercase )[:-1] ) SCREAMING_SNAKE_CASE = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) SCREAMING_SNAKE_CASE = list(__lowercase ) all_models.sort() SCREAMING_SNAKE_CASE = {'model_type': all_models} SCREAMING_SNAKE_CASE = [pt_models[t] for t in all_models] SCREAMING_SNAKE_CASE = [tf_models[t] for t in all_models] SCREAMING_SNAKE_CASE = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure SCREAMING_SNAKE_CASE = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: SCREAMING_SNAKE_CASE = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: SCREAMING_SNAKE_CASE = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: SCREAMING_SNAKE_CASE = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. SCREAMING_SNAKE_CASE = 'AutoTokenizer' SCREAMING_SNAKE_CASE = [processors[t] for t in all_models] return pd.DataFrame(__lowercase ) def __a ( A__ : str ): SCREAMING_SNAKE_CASE = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: SCREAMING_SNAKE_CASE = [model_mapping, F"TF_{model_mapping}", F"FLAX_{model_mapping}"] SCREAMING_SNAKE_CASE = [auto_class, F"TF_{auto_class}", F"Flax_{auto_class}"] # Loop through all three frameworks for module, cls, mapping in zip(__lowercase , __lowercase , __lowercase ): # The type of pipeline may not exist in this framework if not hasattr(__lowercase , __lowercase ): continue # First extract all model_names SCREAMING_SNAKE_CASE = [] for name in getattr(__lowercase , __lowercase ).values(): if isinstance(__lowercase , __lowercase ): model_names.append(__lowercase ) else: model_names.extend(list(__lowercase ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def __a ( A__ : Optional[int] , A__ : Union[str, Any] ): SCREAMING_SNAKE_CASE = get_frameworks_table() SCREAMING_SNAKE_CASE = Dataset.from_pandas(__lowercase ) SCREAMING_SNAKE_CASE = hf_hub_download( "huggingface/transformers-metadata" , "pipeline_tags.json" , repo_type="dataset" , token=__lowercase ) SCREAMING_SNAKE_CASE = Dataset.from_json(__lowercase ) SCREAMING_SNAKE_CASE = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(__lowercase ) ) } SCREAMING_SNAKE_CASE = update_pipeline_and_auto_class_table(__lowercase ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. SCREAMING_SNAKE_CASE = sorted(table.keys() ) SCREAMING_SNAKE_CASE = pd.DataFrame( { "model_class": model_classes, "pipeline_tag": [table[m][0] for m in model_classes], "auto_class": [table[m][1] for m in model_classes], } ) SCREAMING_SNAKE_CASE = Dataset.from_pandas(__lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(__lowercase , "frameworks.json" ) ) tags_dataset.to_json(os.path.join(__lowercase , "pipeline_tags.json" ) ) if commit_sha is not None: SCREAMING_SNAKE_CASE = ( F"Update with commit {commit_sha}\n\nSee: " F"https://github.com/huggingface/transformers/commit/{commit_sha}" ) else: SCREAMING_SNAKE_CASE = 'Update' upload_folder( repo_id="huggingface/transformers-metadata" , folder_path=__lowercase , repo_type="dataset" , token=__lowercase , commit_message=__lowercase , ) def __a ( ): SCREAMING_SNAKE_CASE = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} SCREAMING_SNAKE_CASE = transformers_module.pipelines.SUPPORTED_TASKS SCREAMING_SNAKE_CASE = [] for key in pipeline_tasks: if key not in in_table: SCREAMING_SNAKE_CASE = pipeline_tasks[key]['pt'] if isinstance(__lowercase , (list, tuple) ): SCREAMING_SNAKE_CASE = model[0] SCREAMING_SNAKE_CASE = model.__name__ if model not in in_table.values(): missing.append(__lowercase ) if len(__lowercase ) > 0: SCREAMING_SNAKE_CASE = ', '.join(__lowercase ) raise ValueError( "The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside " F"`utils/update_metadata.py`: {msg}. Please add them!" ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.') parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.') parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.') __A : Optional[Any] = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
704
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __A : Optional[Any] = datasets.load_iris() __A : Optional[Any] = np.array(data['data']) __A : Optional[int] = np.array(data['target']) __A : Union[str, Any] = data['target_names'] __A , __A , __A , __A : Optional[int] = train_test_split(X, y) def __a ( A__ : Optional[int] , A__ : Dict ): return np.linalg.norm(np.array(A__ ) - np.array(A__ ) ) def __a ( A__ : Optional[Any] , A__ : int , A__ : Dict , A__ : Optional[Any] , A__ : Dict=5 ): SCREAMING_SNAKE_CASE = zip(A__ , A__ ) # List of distances of all points from the point to be classified SCREAMING_SNAKE_CASE = [] for data_point in data: SCREAMING_SNAKE_CASE = euclidean_distance(data_point[0] , A__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. SCREAMING_SNAKE_CASE = [i[1] for i in sorted(A__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified SCREAMING_SNAKE_CASE = Counter(A__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
698
0
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _UpperCAmelCase ( ): raise RuntimeError("""CUDA out of memory.""" ) class _lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : Optional[int]): '''simple docstring''' super().__init__() snake_case__ = nn.Linear(3 , 4) snake_case__ = nn.BatchNormad(4) snake_case__ = nn.Linear(4 , 5) def __magic_name__ ( self : Tuple , UpperCamelCase__ : int): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(UpperCamelCase__))) class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __magic_name__ ( self : Tuple): '''simple docstring''' snake_case__ = [] @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(UpperCamelCase__ : List[Any]): nonlocal batch_sizes batch_sizes.append(UpperCamelCase__) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(UpperCamelCase__ , [1_2_8, 6_4, 3_2, 1_6, 8]) def __magic_name__ ( self : int): '''simple docstring''' snake_case__ = [] @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(UpperCamelCase__ : int , UpperCamelCase__ : Optional[int]): nonlocal batch_sizes batch_sizes.append(UpperCamelCase__) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga snake_case__ , snake_case__ = mock_training_loop_function("""hello""") self.assertListEqual(UpperCamelCase__ , [1_2_8, 6_4, 3_2, 1_6, 8]) self.assertListEqual([bs, arga] , [8, """hello"""]) def __magic_name__ ( self : Optional[int]): '''simple docstring''' @find_executable_batch_size(starting_batch_size=0) def mock_training_loop_function(UpperCamelCase__ : Union[str, Any]): pass with self.assertRaises(UpperCamelCase__) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0]) def __magic_name__ ( self : Optional[Any]): '''simple docstring''' @find_executable_batch_size(starting_batch_size=1_6) def mock_training_loop_function(UpperCamelCase__ : List[str]): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(UpperCamelCase__) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0]) def __magic_name__ ( self : Optional[int]): '''simple docstring''' @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any]): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(UpperCamelCase__) as cm: mock_training_loop_function(1_2_8 , """hello""" , """world""") self.assertIn("""Batch size was passed into `f`""" , cm.exception.args[0]) self.assertIn("""`f(arg1='hello', arg2='world')""" , cm.exception.args[0]) def __magic_name__ ( self : Optional[Any]): '''simple docstring''' @find_executable_batch_size(starting_batch_size=1_6) def mock_training_loop_function(UpperCamelCase__ : List[str]): raise ValueError("""Oops, we had an error!""") with self.assertRaises(UpperCamelCase__) as cm: mock_training_loop_function() self.assertIn("""Oops, we had an error!""" , cm.exception.args[0]) @require_cuda def __magic_name__ ( self : List[Any]): '''simple docstring''' snake_case__ = torch.cuda.memory_allocated() snake_case__ = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , UpperCamelCase__) snake_case__ = release_memory(UpperCamelCase__) self.assertEqual(torch.cuda.memory_allocated() , UpperCamelCase__)
654
def _UpperCAmelCase ( a : int ): if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
654
1
'''simple docstring''' import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer lowerCAmelCase__ = logging.get_logger(__name__) class _A ( UpperCamelCase ): '''simple docstring''' _lowercase = 'AutoTokenizer' _lowercase = ['tokenizer'] _lowercase = { 'semantic_prompt': 1, 'coarse_prompt': 2, 'fine_prompt': 2, } def __init__( self : Dict , lowerCamelCase : str , lowerCamelCase : List[Any]=None )-> Dict: super().__init__(lowerCamelCase ) snake_case__ : Optional[int] = speaker_embeddings @classmethod def __lowerCAmelCase ( cls : Optional[int] , lowerCamelCase : Any , lowerCamelCase : Any="speaker_embeddings_path.json" , **lowerCamelCase : List[Any] )-> List[str]: if speaker_embeddings_dict_path is not None: snake_case__ : List[Any] = get_file_from_repo( lowerCamelCase , lowerCamelCase , subfolder=kwargs.pop("""subfolder""" , lowerCamelCase ) , cache_dir=kwargs.pop("""cache_dir""" , lowerCamelCase ) , force_download=kwargs.pop("""force_download""" , lowerCamelCase ) , proxies=kwargs.pop("""proxies""" , lowerCamelCase ) , resume_download=kwargs.pop("""resume_download""" , lowerCamelCase ) , local_files_only=kwargs.pop("""local_files_only""" , lowerCamelCase ) , use_auth_token=kwargs.pop("""use_auth_token""" , lowerCamelCase ) , revision=kwargs.pop("""revision""" , lowerCamelCase ) , ) if speaker_embeddings_path is None: logger.warning( F"""`{os.path.join(lowerCamelCase , lowerCamelCase )}` does not exists , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.""" ) snake_case__ : Dict = None else: with open(lowerCamelCase ) as speaker_embeddings_json: snake_case__ : Optional[Any] = json.load(lowerCamelCase ) else: snake_case__ : List[str] = None snake_case__ : Any = AutoTokenizer.from_pretrained(lowerCamelCase , **lowerCamelCase ) return cls(tokenizer=lowerCamelCase , speaker_embeddings=lowerCamelCase ) def __lowerCAmelCase ( self : Tuple , lowerCamelCase : Optional[Any] , lowerCamelCase : List[Any]="speaker_embeddings_path.json" , lowerCamelCase : int="speaker_embeddings" , lowerCamelCase : bool = False , **lowerCamelCase : Tuple , )-> List[Any]: if self.speaker_embeddings is not None: os.makedirs(os.path.join(lowerCamelCase , lowerCamelCase , """v2""" ) , exist_ok=lowerCamelCase ) snake_case__ : Tuple = {} snake_case__ : List[Any] = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": snake_case__ : List[Any] = self._load_voice_preset(lowerCamelCase ) snake_case__ : int = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["""repo_or_path"""] , lowerCamelCase , F"""{prompt_key}_{key}""" ) , voice_preset[key] , allow_pickle=lowerCamelCase , ) snake_case__ : Union[str, Any] = os.path.join(lowerCamelCase , F"""{prompt_key}_{key}.npy""" ) snake_case__ : Any = tmp_dict with open(os.path.join(lowerCamelCase , lowerCamelCase ) , """w""" ) as fp: json.dump(lowerCamelCase , lowerCamelCase ) super().save_pretrained(lowerCamelCase , lowerCamelCase , **lowerCamelCase ) def __lowerCAmelCase ( self : str , lowerCamelCase : str = None , **lowerCamelCase : Tuple )-> Dict: snake_case__ : int = self.speaker_embeddings[voice_preset] snake_case__ : List[Any] = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F"""Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].""" ) snake_case__ : List[Any] = get_file_from_repo( self.speaker_embeddings.get("""repo_or_path""" , """/""" ) , voice_preset_paths[key] , subfolder=kwargs.pop("""subfolder""" , lowerCamelCase ) , cache_dir=kwargs.pop("""cache_dir""" , lowerCamelCase ) , force_download=kwargs.pop("""force_download""" , lowerCamelCase ) , proxies=kwargs.pop("""proxies""" , lowerCamelCase ) , resume_download=kwargs.pop("""resume_download""" , lowerCamelCase ) , local_files_only=kwargs.pop("""local_files_only""" , lowerCamelCase ) , use_auth_token=kwargs.pop("""use_auth_token""" , lowerCamelCase ) , revision=kwargs.pop("""revision""" , lowerCamelCase ) , ) if path is None: raise ValueError( F"""`{os.path.join(self.speaker_embeddings.get("repo_or_path" , "/" ) , voice_preset_paths[key] )}` does not exists , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset} embeddings.""" ) snake_case__ : Union[str, Any] = np.load(lowerCamelCase ) return voice_preset_dict def __lowerCAmelCase ( self : Tuple , lowerCamelCase : Optional[dict] = None )-> Optional[int]: for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F"""Voice preset unrecognized, missing {key} as a key.""" ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(F"""{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.""" ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F"""{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.""" ) def __call__( self : Dict , lowerCamelCase : List[str]=None , lowerCamelCase : Tuple=None , lowerCamelCase : List[str]="pt" , lowerCamelCase : int=256 , lowerCamelCase : Optional[Any]=False , lowerCamelCase : int=True , lowerCamelCase : Any=False , **lowerCamelCase : Optional[Any] , )-> Tuple: if voice_preset is not None and not isinstance(lowerCamelCase , lowerCamelCase ): if ( isinstance(lowerCamelCase , lowerCamelCase ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): snake_case__ : Tuple = self._load_voice_preset(lowerCamelCase ) else: if isinstance(lowerCamelCase , lowerCamelCase ) and not voice_preset.endswith(""".npz""" ): snake_case__ : List[str] = voice_preset + """.npz""" snake_case__ : Union[str, Any] = np.load(lowerCamelCase ) if voice_preset is not None: self._validate_voice_preset_dict(lowerCamelCase , **lowerCamelCase ) snake_case__ : str = BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase ) snake_case__ : str = self.tokenizer( lowerCamelCase , return_tensors=lowerCamelCase , padding="""max_length""" , max_length=lowerCamelCase , return_attention_mask=lowerCamelCase , return_token_type_ids=lowerCamelCase , add_special_tokens=lowerCamelCase , **lowerCamelCase , ) if voice_preset is not None: snake_case__ : Union[str, Any] = voice_preset return encoded_text
172
'''simple docstring''' import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase__ ( UpperCAmelCase , UpperCAmelCase ): """simple docstring""" snake_case__ : Any = torch.load(UpperCAmelCase , map_location="""cpu""" ) snake_case__ : List[Any] = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository snake_case__ : List[Any] = {} for k, v in state_dict.items(): if "pred_layer" in k: snake_case__ : Union[str, Any] = v else: snake_case__ : str = v snake_case__ : Optional[int] = chkpt["""params"""] snake_case__ : List[Any] = {n: v for n, v in config.items() if not isinstance(UpperCAmelCase , (torch.FloatTensor, numpy.ndarray) )} snake_case__ : Any = chkpt["""dico_word2id"""] snake_case__ : Optional[int] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""" , """""" ): i for s, i in vocab.items()} # Save pytorch-model snake_case__ : str = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME snake_case__ : Optional[int] = pytorch_dump_folder_path + """/""" + CONFIG_NAME snake_case__ : str = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(UpperCAmelCase , UpperCAmelCase ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , indent=2 ) + """\n""" ) print(f"""Save vocab file to {pytorch_config_dump_path}""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , indent=2 ) + """\n""" ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_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.' ) lowerCAmelCase__ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
172
1