code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ): if index == r: for j in range(SCREAMING_SNAKE_CASE__ ): print(data[j] , end=' ' ) print(' ' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __UpperCamelCase =arr[i] combination_util(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , SCREAMING_SNAKE_CASE__ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): # A temporary array to store all combination one by one __UpperCamelCase =[0] * r # Print all combination using temporary array 'data[]' combination_util(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , 0 ) if __name__ == "__main__": # Driver code to check the function above _A = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('multiplicative_persistence() only accepts integral values' ) if num < 0: raise ValueError('multiplicative_persistence() does not accept negative values' ) __UpperCamelCase =0 __UpperCamelCase =str(SCREAMING_SNAKE_CASE__ ) while len(SCREAMING_SNAKE_CASE__ ) != 1: __UpperCamelCase =[int(SCREAMING_SNAKE_CASE__ ) for i in num_string] __UpperCamelCase =1 for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) ): total *= numbers[i] __UpperCamelCase =str(SCREAMING_SNAKE_CASE__ ) steps += 1 return steps def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('additive_persistence() only accepts integral values' ) if num < 0: raise ValueError('additive_persistence() does not accept negative values' ) __UpperCamelCase =0 __UpperCamelCase =str(SCREAMING_SNAKE_CASE__ ) while len(SCREAMING_SNAKE_CASE__ ) != 1: __UpperCamelCase =[int(SCREAMING_SNAKE_CASE__ ) for i in num_string] __UpperCamelCase =0 for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) ): total += numbers[i] __UpperCamelCase =str(SCREAMING_SNAKE_CASE__ ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =20 * np.logaa(SCREAMING_SNAKE_CASE__ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds __UpperCamelCase =get_bounds(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE__ , -2 * pi ) ) plt.show()
62
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
1
from __future__ import annotations from typing import TypedDict class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str UpperCAmelCase__ : int def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('The parameter s type must be str.' ) return [s[i:] + s[:i] for i in range(len(SCREAMING_SNAKE_CASE__ ) )] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('The parameter s type must be str.' ) if not s: raise ValueError('The parameter s must not be empty.' ) __UpperCamelCase =all_rotations(SCREAMING_SNAKE_CASE__ ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation __UpperCamelCase ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(SCREAMING_SNAKE_CASE__ ), } return response def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('The parameter bwt_string type must be str.' ) if not bwt_string: raise ValueError('The parameter bwt_string must not be empty.' ) try: __UpperCamelCase =int(SCREAMING_SNAKE_CASE__ ) except ValueError: raise TypeError( 'The parameter idx_original_string type must be int or passive' ' of cast to int.' ) if idx_original_string < 0: raise ValueError('The parameter idx_original_string must not be lower than 0.' ) if idx_original_string >= len(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'The parameter idx_original_string must be lower than' ' len(bwt_string).' ) __UpperCamelCase =[''] * len(SCREAMING_SNAKE_CASE__ ) for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": _A = 'Provide a string that I will generate its BWT transform: ' _A = input(entry_msg).strip() _A = bwt_transform(s) print( f"""Burrows Wheeler transform for string '{s}' results """ f"""in '{result['bwt_string']}'""" ) _A = reverse_bwt(result['bwt_string'], result['idx_original_string']) print( f"""Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' """ f"""we get original string '{original_string}'""" )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _A = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , *A_ , **A_ ) -> None: warnings.warn( 'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use LayoutLMv2ImageProcessor instead.' , A_ , ) super().__init__(*A_ , **A_ )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Any = LxmertTokenizer UpperCAmelCase__ : Union[str, Any] = LxmertTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : Dict = True def _a ( self ) -> str: super().setUp() __UpperCamelCase =[ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __UpperCamelCase =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] ) ) def _a ( self , A_ ) -> str: __UpperCamelCase ='UNwant\u00E9d,running' __UpperCamelCase ='unwanted, running' return input_text, output_text def _a ( self ) -> Optional[int]: __UpperCamelCase =self.tokenizer_class(self.vocab_file ) __UpperCamelCase =tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(A_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Union[str, Any]: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =tokenizer.tokenize(A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase =tokenizer.encode(A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ )
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): while y: # --> when y=0 then loop will terminate and return x as final GCD. __UpperCamelCase , __UpperCamelCase =y, x % y return abs(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): try: __UpperCamelCase =input('Enter two integers separated by comma (,): ' ).split(',' ) __UpperCamelCase =int(nums[0] ) __UpperCamelCase =int(nums[1] ) print( F'greatest_common_divisor({num_a}, {num_a}) = ' F'{greatest_common_divisor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )}' ) print(F'By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )}' ) except (IndexError, UnboundLocalError, ValueError): print('Wrong input' ) if __name__ == "__main__": main()
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =20 * np.logaa(SCREAMING_SNAKE_CASE__ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds __UpperCamelCase =get_bounds(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE__ , -2 * pi ) ) plt.show()
62
1
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): return params[F'{prefix}/{prefix}/relpos_bias/rel_embedding'][:, i, :] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any="attention" ): __UpperCamelCase =__UpperCamelCase =np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/key/kernel'][:, i, :, :] ) __UpperCamelCase =k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) __UpperCamelCase =np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/out/kernel'][:, i, :, :] ) __UpperCamelCase =o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) __UpperCamelCase =np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/query/kernel'][:, i, :, :] ) __UpperCamelCase =q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) __UpperCamelCase =np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/value/kernel'][:, i, :, :] ) __UpperCamelCase =v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any]=False ): if split_mlp_wi: __UpperCamelCase =params[F'{prefix}/{prefix}/mlp/wi_0/kernel'][:, i, :] __UpperCamelCase =params[F'{prefix}/{prefix}/mlp/wi_1/kernel'][:, i, :] __UpperCamelCase =(wi_a, wi_a) else: __UpperCamelCase =params[F'{prefix}/{prefix}/mlp/wi/kernel'][:, i, :] __UpperCamelCase =params[F'{prefix}/{prefix}/mlp/wo/kernel'][:, i, :] return wi, wo def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] ): return params[F'{prefix}/{prefix}/{layer_name}/scale'][:, i] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict , *, SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : bool = False ): __UpperCamelCase =traverse_util.flatten_dict(variables['target'] ) __UpperCamelCase ={'/'.join(SCREAMING_SNAKE_CASE__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi __UpperCamelCase ='encoder/encoder/mlp/wi_0/kernel' in old print('Split MLP:' , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =collections.OrderedDict() # Shared embeddings. __UpperCamelCase =old['token_embedder/embedding'] # Encoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). __UpperCamelCase =tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , 'pre_attention_layer_norm' ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , 'attention' ) __UpperCamelCase =layer_norm __UpperCamelCase =k.T __UpperCamelCase =o.T __UpperCamelCase =q.T __UpperCamelCase =v.T # Block i, layer 1 (MLP). __UpperCamelCase =tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , 'pre_mlp_layer_norm' ) __UpperCamelCase , __UpperCamelCase =tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =layer_norm if split_mlp_wi: __UpperCamelCase =wi[0].T __UpperCamelCase =wi[1].T else: __UpperCamelCase =wi.T __UpperCamelCase =wo.T if scalable_attention: # convert the rel_embedding of each layer __UpperCamelCase =tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' ).T __UpperCamelCase =old['encoder/encoder_norm/scale'] if not scalable_attention: __UpperCamelCase =tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , 0 , 'encoder' ).T __UpperCamelCase =tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , 0 , 'decoder' ).T if not is_encoder_only: # Decoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). __UpperCamelCase =tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'pre_self_attention_layer_norm' ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'self_attention' ) __UpperCamelCase =layer_norm __UpperCamelCase =k.T __UpperCamelCase =o.T __UpperCamelCase =q.T __UpperCamelCase =v.T # Block i, layer 1 (Cross Attention). __UpperCamelCase =tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'pre_cross_attention_layer_norm' ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'encoder_decoder_attention' ) __UpperCamelCase =layer_norm __UpperCamelCase =k.T __UpperCamelCase =o.T __UpperCamelCase =q.T __UpperCamelCase =v.T # Block i, layer 2 (MLP). __UpperCamelCase =tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'pre_mlp_layer_norm' ) __UpperCamelCase , __UpperCamelCase =tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =layer_norm if split_mlp_wi: __UpperCamelCase =wi[0].T __UpperCamelCase =wi[1].T else: __UpperCamelCase =wi.T __UpperCamelCase =wo.T if scalable_attention: # convert the rel_embedding of each layer __UpperCamelCase =tax_relpos_bias_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' ).T __UpperCamelCase =old['decoder/decoder_norm/scale'] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: __UpperCamelCase =old['decoder/logits_dense/kernel'].T return new def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool ): __UpperCamelCase =collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: __UpperCamelCase =state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: __UpperCamelCase =state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) __UpperCamelCase =state_dict['shared.weight'] return state_dict def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =convert_tax_to_pytorch( SCREAMING_SNAKE_CASE__ , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE__ , scalable_attention=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =make_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ): __UpperCamelCase =MTaConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(F'Building PyTorch model from configuration: {config}' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: __UpperCamelCase =UMTaEncoderModel(SCREAMING_SNAKE_CASE__ ) else: __UpperCamelCase =UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Verify that we can load the checkpoint. model.from_pretrained(SCREAMING_SNAKE_CASE__ ) print('Done' ) if __name__ == "__main__": _A = argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.') # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False ) parser.add_argument( '--scalable_attention', action='store_true', help='Whether the model uses scaled attention (umt5 model)', default=False, ) _A = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() def _a ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase =FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-canny' , from_pt=A_ , dtype=jnp.bfloataa ) __UpperCamelCase , __UpperCamelCase =FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=A_ , from_pt=A_ , dtype=jnp.bfloataa ) __UpperCamelCase =controlnet_params __UpperCamelCase ='bird' __UpperCamelCase =jax.device_count() __UpperCamelCase =pipe.prepare_text_inputs([prompts] * num_samples ) __UpperCamelCase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ) __UpperCamelCase =pipe.prepare_image_inputs([canny_image] * num_samples ) __UpperCamelCase =jax.random.PRNGKey(0 ) __UpperCamelCase =jax.random.split(A_ , jax.device_count() ) __UpperCamelCase =replicate(A_ ) __UpperCamelCase =shard(A_ ) __UpperCamelCase =shard(A_ ) __UpperCamelCase =pipe( prompt_ids=A_ , image=A_ , params=A_ , prng_seed=A_ , num_inference_steps=50 , jit=A_ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __UpperCamelCase =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __UpperCamelCase =images[0, 253:256, 253:256, -1] __UpperCamelCase =jnp.asarray(jax.device_get(image_slice.flatten() ) ) __UpperCamelCase =jnp.array( [0.16_7969, 0.11_6699, 0.08_1543, 0.15_4297, 0.13_2812, 0.10_8887, 0.16_9922, 0.16_9922, 0.20_5078] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[Any]: __UpperCamelCase , __UpperCamelCase =FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-openpose' , from_pt=A_ , dtype=jnp.bfloataa ) __UpperCamelCase , __UpperCamelCase =FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=A_ , from_pt=A_ , dtype=jnp.bfloataa ) __UpperCamelCase =controlnet_params __UpperCamelCase ='Chef in the kitchen' __UpperCamelCase =jax.device_count() __UpperCamelCase =pipe.prepare_text_inputs([prompts] * num_samples ) __UpperCamelCase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png' ) __UpperCamelCase =pipe.prepare_image_inputs([pose_image] * num_samples ) __UpperCamelCase =jax.random.PRNGKey(0 ) __UpperCamelCase =jax.random.split(A_ , jax.device_count() ) __UpperCamelCase =replicate(A_ ) __UpperCamelCase =shard(A_ ) __UpperCamelCase =shard(A_ ) __UpperCamelCase =pipe( prompt_ids=A_ , image=A_ , params=A_ , prng_seed=A_ , num_inference_steps=50 , jit=A_ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __UpperCamelCase =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __UpperCamelCase =images[0, 253:256, 253:256, -1] __UpperCamelCase =jnp.asarray(jax.device_get(image_slice.flatten() ) ) __UpperCamelCase =jnp.array( [[0.27_1484, 0.26_1719, 0.27_5391, 0.27_7344, 0.27_9297, 0.29_1016, 0.29_4922, 0.30_2734, 0.30_2734]] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( 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_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =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.' )
62
1
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
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
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Any: __UpperCamelCase ='hf-internal-testing/tiny-random-t5' __UpperCamelCase =AutoTokenizer.from_pretrained(A_ ) __UpperCamelCase =AutoModelForSeqaSeqLM.from_pretrained(A_ ) __UpperCamelCase =tokenizer('This is me' , return_tensors='pt' ) __UpperCamelCase =model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) __UpperCamelCase =model.generate(**A_ ) __UpperCamelCase =model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(A_ ) __UpperCamelCase =AutoModelForSeqaSeqLM.from_pretrained(A_ ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) __UpperCamelCase =model_reloaded.generate(**A_ ) self.assertTrue(torch.allclose(A_ , A_ ) ) def _a ( self ) -> str: __UpperCamelCase ='hf-internal-testing/tiny-random-t5' __UpperCamelCase =AutoModelForSeqaSeqLM.from_pretrained(A_ ) __UpperCamelCase =model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(A_ ): model.save_pretrained(A_ ) __UpperCamelCase =model.reverse_bettertransformer() model.save_pretrained(A_ )
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): return [sentence[i : i + ngram_size] for i in range(len(SCREAMING_SNAKE_CASE__ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[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] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class UpperCAmelCase__ ( A_ , A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = StableDiffusionControlNetImgaImgPipeline UpperCAmelCase__ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} UpperCAmelCase__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCAmelCase__ : str = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"} ) UpperCAmelCase__ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _a ( self ) -> str: torch.manual_seed(0 ) __UpperCamelCase =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) torch.manual_seed(0 ) __UpperCamelCase =ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) __UpperCamelCase =DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=A_ , set_alpha_to_one=A_ , ) torch.manual_seed(0 ) __UpperCamelCase =AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCamelCase =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __UpperCamelCase =CLIPTextModel(A_ ) __UpperCamelCase =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __UpperCamelCase ={ 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _a ( self , A_ , A_=0 ) -> Dict: if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase =2 __UpperCamelCase =randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=A_ , device=torch.device(A_ ) , ) __UpperCamelCase =floats_tensor(control_image.shape , rng=random.Random(A_ ) ).to(A_ ) __UpperCamelCase =image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCamelCase =Image.fromarray(np.uinta(A_ ) ).convert('RGB' ).resize((64, 64) ) __UpperCamelCase ={ 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def _a ( self ) -> Tuple: return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def _a ( self ) -> int: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _a ( self ) -> int: self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class UpperCAmelCase__ ( A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = StableDiffusionControlNetImgaImgPipeline UpperCAmelCase__ : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} UpperCAmelCase__ : Any = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCAmelCase__ : Union[str, Any] = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _a ( self ) -> Union[str, Any]: torch.manual_seed(0 ) __UpperCamelCase =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(A_ ): if isinstance(A_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) __UpperCamelCase =ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(A_ ) torch.manual_seed(0 ) __UpperCamelCase =ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(A_ ) torch.manual_seed(0 ) __UpperCamelCase =DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=A_ , set_alpha_to_one=A_ , ) torch.manual_seed(0 ) __UpperCamelCase =AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCamelCase =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __UpperCamelCase =CLIPTextModel(A_ ) __UpperCamelCase =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __UpperCamelCase =MultiControlNetModel([controlneta, controlneta] ) __UpperCamelCase ={ 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _a ( self , A_ , A_=0 ) -> List[str]: if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase =2 __UpperCamelCase =[ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=A_ , device=torch.device(A_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=A_ , device=torch.device(A_ ) , ), ] __UpperCamelCase =floats_tensor(control_image[0].shape , rng=random.Random(A_ ) ).to(A_ ) __UpperCamelCase =image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCamelCase =Image.fromarray(np.uinta(A_ ) ).convert('RGB' ).resize((64, 64) ) __UpperCamelCase ={ 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) pipe.to(A_ ) __UpperCamelCase =10.0 __UpperCamelCase =4 __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =steps __UpperCamelCase =scale __UpperCamelCase =pipe(**A_ )[0] __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =steps __UpperCamelCase =scale __UpperCamelCase =pipe(**A_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =steps __UpperCamelCase =scale __UpperCamelCase =pipe(**A_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =steps __UpperCamelCase =scale __UpperCamelCase =pipe(**A_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _a ( self ) -> List[str]: return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def _a ( self ) -> Dict: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _a ( self ) -> str: self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(A_ ) except NotImplementedError: pass @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Union[str, Any]: __UpperCamelCase =ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny' ) __UpperCamelCase =StableDiffusionControlNetImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , safety_checker=A_ , controlnet=A_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase ='evil space-punk bird' __UpperCamelCase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ).resize((512, 512) ) __UpperCamelCase =load_image( 'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png' ).resize((512, 512) ) __UpperCamelCase =pipe( A_ , A_ , control_image=A_ , generator=A_ , output_type='np' , num_inference_steps=50 , strength=0.6 , ) __UpperCamelCase =output.images[0] assert image.shape == (512, 512, 3) __UpperCamelCase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy' ) assert np.abs(expected_image - image ).max() < 9E-2
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = field(default="language-modeling" , metadata={"include_in_asdict_even_if_is_default": True} ) UpperCAmelCase__ : ClassVar[Features] = Features({"text": Value("string" )} ) UpperCAmelCase__ : ClassVar[Features] = Features({} ) UpperCAmelCase__ : str = "text" @property def _a ( self ) -> Dict[str, str]: return {self.text_column: "text"}
62
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ) -> PIL.Image.Image: __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(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =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.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ShapEImgaImgPipeline UpperCAmelCase__ : int = ["image"] UpperCAmelCase__ : List[str] = ["image"] UpperCAmelCase__ : int = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] UpperCAmelCase__ : List[Any] = False @property def _a ( self ) -> Tuple: return 32 @property def _a ( self ) -> int: return 32 @property def _a ( self ) -> Optional[int]: return self.time_input_dim * 4 @property def _a ( self ) -> Any: return 8 @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase =CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __UpperCamelCase =CLIPVisionModel(A_ ) return model @property def _a ( self ) -> List[Any]: __UpperCamelCase =CLIPImageProcessor( crop_size=224 , do_center_crop=A_ , do_normalize=A_ , do_resize=A_ , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor @property def _a ( self ) -> str: torch.manual_seed(0 ) __UpperCamelCase ={ 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'embedding_proj_norm_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __UpperCamelCase =PriorTransformer(**A_ ) return model @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase ={ 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __UpperCamelCase =ShapERenderer(**A_ ) return model def _a ( self ) -> List[str]: __UpperCamelCase =self.dummy_prior __UpperCamelCase =self.dummy_image_encoder __UpperCamelCase =self.dummy_image_processor __UpperCamelCase =self.dummy_renderer __UpperCamelCase =HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=A_ , clip_sample=A_ , clip_sample_range=1.0 , ) __UpperCamelCase ={ 'prior': prior, 'image_encoder': image_encoder, 'image_processor': image_processor, 'renderer': renderer, 'scheduler': scheduler, } return components def _a ( self , A_ , A_=0 ) -> Any: __UpperCamelCase =floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase ={ 'image': input_image, 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def _a ( self ) -> str: __UpperCamelCase ='cpu' __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) __UpperCamelCase =pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =pipe(**self.get_dummy_inputs(A_ ) ) __UpperCamelCase =output.images[0] __UpperCamelCase =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __UpperCamelCase =np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> int: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _a ( self ) -> List[str]: __UpperCamelCase =torch_device == 'cpu' __UpperCamelCase =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=A_ , relax_max_difference=A_ , ) def _a ( self ) -> Tuple: __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) __UpperCamelCase =pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =1 __UpperCamelCase =2 __UpperCamelCase =self.get_dummy_inputs(A_ ) for key in inputs.keys(): if key in self.batch_params: __UpperCamelCase =batch_size * [inputs[key]] __UpperCamelCase =pipe(**A_ , num_images_per_prompt=A_ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> int: __UpperCamelCase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png' ) __UpperCamelCase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_img2img_out.npy' ) __UpperCamelCase =ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img' ) __UpperCamelCase =pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(0 ) __UpperCamelCase =pipe( A_ , generator=A_ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(A_ , A_ )
62
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 _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging _A = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ ) -> Optional[int]: super().__init__() __UpperCamelCase =nn.ModuleList(A_ ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = False , A_ = True , ) -> Union[ControlNetOutput, Tuple]: for i, (image, scale, controlnet) in enumerate(zip(A_ , A_ , self.nets ) ): __UpperCamelCase , __UpperCamelCase =controlnet( A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) # merge samples if i == 0: __UpperCamelCase , __UpperCamelCase =down_samples, mid_sample else: __UpperCamelCase =[ samples_prev + samples_curr for samples_prev, samples_curr in zip(A_ , A_ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def _a ( self , A_ , A_ = True , A_ = None , A_ = False , A_ = None , ) -> Optional[Any]: __UpperCamelCase =0 __UpperCamelCase =save_directory for controlnet in self.nets: controlnet.save_pretrained( A_ , is_main_process=A_ , save_function=A_ , safe_serialization=A_ , variant=A_ , ) idx += 1 __UpperCamelCase =model_path_to_save + f'_{idx}' @classmethod def _a ( cls , A_ , **A_ ) -> List[str]: __UpperCamelCase =0 __UpperCamelCase =[] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __UpperCamelCase =pretrained_model_path while os.path.isdir(A_ ): __UpperCamelCase =ControlNetModel.from_pretrained(A_ , **A_ ) controlnets.append(A_ ) idx += 1 __UpperCamelCase =pretrained_model_path + f'_{idx}' logger.info(f'{len(A_ )} controlnets loaded from {pretrained_model_path}.' ) if len(A_ ) == 0: raise ValueError( f'No ControlNets found under {os.path.dirname(A_ )}. Expected at least {pretrained_model_path + "_0"}.' ) return cls(A_ )
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Union[str, Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ ) model.generate(A_ , max_new_tokens=10 , do_sample=A_ , streamer=A_ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __UpperCamelCase =cs.out[:-1] self.assertEqual(A_ , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =tokenizer.decode(greedy_ids[0] ) __UpperCamelCase =TextIteratorStreamer(A_ ) __UpperCamelCase ={'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} __UpperCamelCase =Thread(target=model.generate , kwargs=A_ ) thread.start() __UpperCamelCase ='' for new_text in streamer: streamer_text += new_text self.assertEqual(A_ , A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =greedy_ids[:, input_ids.shape[1] :] __UpperCamelCase =tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ , skip_prompt=A_ ) model.generate(A_ , max_new_tokens=10 , do_sample=A_ , streamer=A_ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __UpperCamelCase =cs.out[:-1] self.assertEqual(A_ , A_ ) def _a ( self ) -> Any: # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them __UpperCamelCase =AutoTokenizer.from_pretrained('distilgpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('distilgpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =torch.ones((1, 5) , device=A_ ).long() * model.config.bos_token_id with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ , skip_special_tokens=A_ ) model.generate(A_ , max_new_tokens=1 , do_sample=A_ , streamer=A_ ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token __UpperCamelCase =cs.out[:-1] # Remove the final "\n" __UpperCamelCase =tokenizer(A_ , return_tensors='pt' ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _a ( self ) -> Tuple: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =TextIteratorStreamer(A_ , timeout=0.001 ) __UpperCamelCase ={'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} __UpperCamelCase =Thread(target=model.generate , kwargs=A_ ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(A_ ): __UpperCamelCase ='' for new_text in streamer: streamer_text += new_text
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple ): __UpperCamelCase , __UpperCamelCase =[], [] while len(SCREAMING_SNAKE_CASE__ ) > 1: __UpperCamelCase , __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ ), max(SCREAMING_SNAKE_CASE__ ) start.append(SCREAMING_SNAKE_CASE__ ) end.append(SCREAMING_SNAKE_CASE__ ) collection.remove(SCREAMING_SNAKE_CASE__ ) collection.remove(SCREAMING_SNAKE_CASE__ ) end.reverse() return start + collection + end if __name__ == "__main__": _A = input('Enter numbers separated by a comma:\n').strip() _A = [int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',')
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __UpperCamelCase =FileLock(str(tmpdir / 'foo.lock' ) ) __UpperCamelCase =FileLock(str(tmpdir / 'foo.lock' ) ) __UpperCamelCase =0.01 with locka.acquire(): with pytest.raises(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =time.time() locka.acquire(SCREAMING_SNAKE_CASE__ ) assert time.time() - _start > timeout def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase ='a' * 10_00 + '.lock' __UpperCamelCase =FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('.lock' ) assert not locka._lock_file.endswith(SCREAMING_SNAKE_CASE__ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_55 __UpperCamelCase =FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(SCREAMING_SNAKE_CASE__ ): locka.acquire(0 )
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
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 _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _A = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self , A_ , A_ , A_ = None , A_ = None ) -> Optional[Any]: __UpperCamelCase =None __UpperCamelCase =os.path.abspath(os.path.join('examples' , 'by_feature' ) ) __UpperCamelCase =os.path.abspath('examples' ) for item in os.listdir(A_ ): if item not in EXCLUDE_EXAMPLES: __UpperCamelCase =os.path.join(A_ , A_ ) if os.path.isfile(A_ ) and ".py" in item_path: with self.subTest( tested_script=A_ , feature_script=A_ , tested_section='main()' if parser_only else 'training_function()' , ): __UpperCamelCase =compare_against_test( os.path.join(A_ , A_ ) , A_ , A_ , A_ ) __UpperCamelCase ='\n'.join(A_ ) if special_strings is not None: for string in special_strings: __UpperCamelCase =diff.replace(A_ , '' ) self.assertEqual(A_ , '' ) def _a ( self ) -> Dict: self.one_complete_example('complete_nlp_example.py' , A_ ) self.one_complete_example('complete_nlp_example.py' , A_ ) def _a ( self ) -> Dict: __UpperCamelCase =os.path.abspath(os.path.join('examples' , 'cv_example.py' ) ) __UpperCamelCase =[ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , A_ , A_ , A_ ) self.one_complete_example('complete_cv_example.py' , A_ , A_ , A_ ) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Tuple = False @classmethod def _a ( cls ) -> Union[str, Any]: super().setUpClass() __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =os.path.join(cls._tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __UpperCamelCase =['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def _a ( cls ) -> Union[str, Any]: super().tearDownClass() shutil.rmtree(cls._tmpdir ) def _a ( self ) -> List[Any]: __UpperCamelCase =f'\n examples/by_feature/checkpointing.py\n --checkpointing_steps epoch\n --output_dir {self.tmpdir}\n '.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0' ) ) ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =f'\n examples/by_feature/checkpointing.py\n --checkpointing_steps 1\n --output_dir {self.tmpdir}\n '.split() __UpperCamelCase =run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2' ) ) ) def _a ( self ) -> Tuple: __UpperCamelCase =f'\n examples/by_feature/checkpointing.py\n --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )}\n '.split() __UpperCamelCase =run_command(self._launch_args + testargs , return_stdout=A_ ) self.assertNotIn('epoch 0:' , A_ ) self.assertIn('epoch 1:' , A_ ) def _a ( self ) -> int: __UpperCamelCase =f'\n examples/by_feature/checkpointing.py\n --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )}\n '.split() __UpperCamelCase =run_command(self._launch_args + testargs , return_stdout=A_ ) if torch.cuda.is_available(): __UpperCamelCase =torch.cuda.device_count() else: __UpperCamelCase =1 if num_processes > 1: self.assertNotIn('epoch 0:' , A_ ) self.assertIn('epoch 1:' , A_ ) else: self.assertIn('epoch 0:' , A_ ) self.assertIn('epoch 1:' , A_ ) @slow def _a ( self ) -> Optional[Any]: __UpperCamelCase ='\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'} ): __UpperCamelCase =run_command(self._launch_args + testargs , return_stdout=A_ ) __UpperCamelCase =re.findall('({.+})' , A_ ) __UpperCamelCase =[r for r in results if 'accuracy' in r][-1] __UpperCamelCase =ast.literal_eval(A_ ) self.assertGreaterEqual(results['accuracy'] , 0.75 ) def _a ( self ) -> str: __UpperCamelCase =['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def _a ( self ) -> List[str]: with tempfile.TemporaryDirectory() as tmpdir: __UpperCamelCase =f'\n examples/by_feature/tracking.py\n --with_tracking\n --project_dir {tmpdir}\n '.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(A_ , 'tracking' ) ) ) def _a ( self ) -> Optional[int]: __UpperCamelCase =['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs ) def _a ( self ) -> List[Any]: __UpperCamelCase =['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs )
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =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] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): _A = 'pt' elif is_tf_available(): _A = 'tf' else: _A = 'jax' class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = ByTaTokenizer UpperCAmelCase__ : List[Any] = False def _a ( self ) -> Any: super().setUp() __UpperCamelCase =ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _a ( self ) -> Any: return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _a ( self , **A_ ) -> ByTaTokenizer: return self.tokenizer_class.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ , A_=False , A_=20 , A_=5 ) -> Tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for ByT5 because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. __UpperCamelCase =[] for i in range(len(A_ ) ): try: __UpperCamelCase =tokenizer.decode([i] , clean_up_tokenization_spaces=A_ ) except UnicodeDecodeError: pass toks.append((i, tok) ) __UpperCamelCase =list(filter(lambda A_ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , A_ ) ) __UpperCamelCase =list(filter(lambda A_ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=A_ ) , A_ ) ) if max_length is not None and len(A_ ) > max_length: __UpperCamelCase =toks[:max_length] if min_length is not None and len(A_ ) < min_length and len(A_ ) > 0: while len(A_ ) < min_length: __UpperCamelCase =toks + toks # toks_str = [t[1] for t in toks] __UpperCamelCase =[t[0] for t in toks] # Ensure consistency __UpperCamelCase =tokenizer.decode(A_ , clean_up_tokenization_spaces=A_ ) if " " not in output_txt and len(A_ ) > 1: __UpperCamelCase =( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=A_ ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=A_ ) ) if with_prefix_space: __UpperCamelCase =' ' + output_txt __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) return output_txt, output_ids def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.ta_base_tokenizer __UpperCamelCase =tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) __UpperCamelCase =tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _a ( self ) -> Any: __UpperCamelCase =self.ta_base_tokenizer __UpperCamelCase ='Unicode €.' __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['input_ids'] , A_ ) # decoding __UpperCamelCase =tokenizer.decode(A_ ) self.assertEqual(A_ , 'Unicode €.</s>' ) __UpperCamelCase =tokenizer('e è é ê ë' ) __UpperCamelCase =[104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['input_ids'] , A_ ) # decoding __UpperCamelCase =tokenizer.decode(A_ ) self.assertEqual(A_ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _a ( self ) -> Any: __UpperCamelCase =self.ta_base_tokenizer __UpperCamelCase =['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off __UpperCamelCase =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on __UpperCamelCase =tokenizer(A_ , padding=A_ , return_tensors=A_ ) self.assertIsInstance(A_ , A_ ) if FRAMEWORK != "jax": __UpperCamelCase =list(batch.input_ids.numpy()[0] ) else: __UpperCamelCase =list(batch.input_ids.tolist()[0] ) self.assertListEqual(A_ , A_ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _a ( self ) -> List[str]: __UpperCamelCase =self.ta_base_tokenizer __UpperCamelCase =['A long paragraph for summarization.', 'Another paragraph for summarization.'] __UpperCamelCase =tokenizer(A_ , padding=A_ , return_tensors=A_ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , A_ ) self.assertIn('attention_mask' , A_ ) self.assertNotIn('decoder_input_ids' , A_ ) self.assertNotIn('decoder_attention_mask' , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.ta_base_tokenizer __UpperCamelCase =[ 'Summary of the text.', 'Another summary.', ] __UpperCamelCase =tokenizer( text_target=A_ , max_length=32 , padding='max_length' , truncation=A_ , return_tensors=A_ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.ta_base_tokenizer __UpperCamelCase =['A long paragraph for summarization. </s>'] __UpperCamelCase =['Summary of the text. </s>'] # fmt: off __UpperCamelCase =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] __UpperCamelCase =[86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on __UpperCamelCase =tokenizer(A_ , text_target=A_ ) self.assertEqual(A_ , batch['input_ids'][0] ) self.assertEqual(A_ , batch['labels'][0] ) def _a ( self ) -> Tuple: # safety check on max_len default value so we are sure the test works __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =' He is very happy, UNwant\u00E9d,running' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) tokenizer.save_pretrained(A_ ) __UpperCamelCase =tokenizer.__class__.from_pretrained(A_ ) __UpperCamelCase =after_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) shutil.rmtree(A_ ) __UpperCamelCase =self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) __UpperCamelCase =tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) tokenizer.save_pretrained(A_ ) __UpperCamelCase =tokenizer.__class__.from_pretrained(A_ ) __UpperCamelCase =after_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) __UpperCamelCase =tokenizer.__class__.from_pretrained(A_ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(A_ ) with open(os.path.join(A_ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: __UpperCamelCase =json.load(A_ ) with open(os.path.join(A_ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: __UpperCamelCase =json.load(A_ ) __UpperCamelCase =[f'<extra_id_{i}>' for i in range(125 )] __UpperCamelCase =added_tokens_extra_ids + [ 'an_additional_special_token' ] __UpperCamelCase =added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(A_ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(A_ , A_ ) with open(os.path.join(A_ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(A_ , A_ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __UpperCamelCase =tokenizer_class.from_pretrained( A_ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __UpperCamelCase =added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=A_ )] __UpperCamelCase =tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _a ( self ) -> List[Any]: __UpperCamelCase =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(A_ ) __UpperCamelCase =tokenizer_class.from_pretrained(A_ ) self.assertTrue(tokenizer.decode([255] ) == '' ) def _a ( self ) -> int: pass def _a ( self ) -> Tuple: pass def _a ( self ) -> Tuple: pass def _a ( self ) -> List[Any]: pass def _a ( self ) -> List[str]: # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings # and special added tokens as tokens __UpperCamelCase =self.get_tokenizers(fast=A_ , do_lower_case=A_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase =['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] __UpperCamelCase =tokenizer.convert_tokens_to_string(A_ ) self.assertIsInstance(A_ , A_ ) def _a ( self ) -> Any: __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase =[ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] __UpperCamelCase =0 __UpperCamelCase =tokenizer.convert_ids_to_tokens( A_ , skip_special_tokens=A_ ) for attr in attributes_list: setattr(A_ , attr + '_id' , A_ ) self.assertEqual(getattr(A_ , A_ ) , A_ ) self.assertEqual(getattr(A_ , attr + '_id' ) , A_ ) setattr(A_ , attr + '_id' , A_ ) self.assertEqual(getattr(A_ , A_ ) , A_ ) self.assertEqual(getattr(A_ , attr + '_id' ) , A_ ) setattr(A_ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(A_ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(A_ , 'additional_special_tokens_ids' ) , [] ) setattr(A_ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(A_ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(A_ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from datetime import datetime import matplotlib.pyplot as plt import torch def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): for param in module.parameters(): __UpperCamelCase =False def _UpperCAmelCase ( ): __UpperCamelCase ='cuda' if torch.cuda.is_available() else 'cpu' if torch.backends.mps.is_available() and torch.backends.mps.is_built(): __UpperCamelCase ='mps' if device == "mps": print( 'WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch' ' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues' ' with generations.' ) return device def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =plt.imshow(SCREAMING_SNAKE_CASE__ ) fig.axes.get_xaxis().set_visible(SCREAMING_SNAKE_CASE__ ) fig.axes.get_yaxis().set_visible(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( ): __UpperCamelCase =datetime.now() __UpperCamelCase =current_time.strftime('%H:%M:%S' ) return timestamp
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[List[PIL.Image.Image], np.ndarray] UpperCAmelCase__ : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer 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 StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : np.ndarray UpperCAmelCase__ : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
62
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = StableDiffusionLDMaDPipeline UpperCAmelCase__ : Tuple = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__ : Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase__ : str = TEXT_TO_IMAGE_IMAGE_PARAMS def _a ( self ) -> Union[str, Any]: torch.manual_seed(0 ) __UpperCamelCase =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) __UpperCamelCase =DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=A_ , set_alpha_to_one=A_ , ) torch.manual_seed(0 ) __UpperCamelCase =AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCamelCase =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __UpperCamelCase =CLIPTextModel(A_ ) __UpperCamelCase =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __UpperCamelCase ={ 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _a ( self , A_ , A_=0 ) -> List[str]: if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase ={ 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def _a ( self ) -> Dict: __UpperCamelCase ='cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =StableDiffusionLDMaDPipeline(**A_ ) __UpperCamelCase =ldmad_pipe.to(A_ ) ldmad_pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =ldmad_pipe(**A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =rgb[0, -3:, -3:, -1] __UpperCamelCase =depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) __UpperCamelCase =np.array( [0.3733_8176, 0.7_0247, 0.7420_3193, 0.5164_3604, 0.5825_6793, 0.6093_2136, 0.418_1095, 0.4835_5877, 0.4653_5262] ) __UpperCamelCase =np.array([103.4_6727, 85.81_2004, 87.84_9236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1E-2 def _a ( self ) -> str: __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =StableDiffusionLDMaDPipeline(**A_ ) __UpperCamelCase =ldmad_pipe.to(A_ ) ldmad_pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =3 * [inputs['prompt']] # forward __UpperCamelCase =ldmad_pipe(**A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =rgb_slice_a[0, -3:, -3:, -1] __UpperCamelCase =depth_slice_a[0, -3:, -1] __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =3 * [inputs.pop('prompt' )] __UpperCamelCase =ldmad_pipe.tokenizer( A_ , padding='max_length' , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=A_ , return_tensors='pt' , ) __UpperCamelCase =text_inputs['input_ids'].to(A_ ) __UpperCamelCase =ldmad_pipe.text_encoder(A_ )[0] __UpperCamelCase =prompt_embeds # forward __UpperCamelCase =ldmad_pipe(**A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =rgb_slice_a[0, -3:, -3:, -1] __UpperCamelCase =depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1E-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1E-4 def _a ( self ) -> Optional[Any]: __UpperCamelCase ='cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =PNDMScheduler(skip_prk_steps=A_ ) __UpperCamelCase =StableDiffusionLDMaDPipeline(**A_ ) __UpperCamelCase =ldmad_pipe.to(A_ ) ldmad_pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase ='french fries' __UpperCamelCase =ldmad_pipe(**A_ , negative_prompt=A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =rgb[0, -3:, -3:, -1] __UpperCamelCase =depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) __UpperCamelCase =np.array( [0.3_7044, 0.7181_1503, 0.722_3251, 0.4860_3675, 0.563_8391, 0.636_4948, 0.4283_3704, 0.490_1315, 0.4792_6217] ) __UpperCamelCase =np.array([107.8_4738, 84.6_2802, 89.96_2135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1E-2 @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self , A_ , A_="cpu" , A_=torch.floataa , A_=0 ) -> int: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase =np.random.RandomState(A_ ).standard_normal((1, 4, 64, 64) ) __UpperCamelCase =torch.from_numpy(A_ ).to(device=A_ , dtype=A_ ) __UpperCamelCase ={ 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _a ( self ) -> Optional[int]: __UpperCamelCase =StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ) __UpperCamelCase =ldmad_pipe.to(A_ ) ldmad_pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_inputs(A_ ) __UpperCamelCase =ldmad_pipe(**A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =rgb[0, -3:, -3:, -1].flatten() __UpperCamelCase =rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) __UpperCamelCase =np.array( [0.5380_5465, 0.5670_7305, 0.548_6515, 0.5701_2236, 0.581_4511, 0.5625_3487, 0.5484_3014, 0.5509_2263, 0.645_9706] ) __UpperCamelCase =np.array( [0.926_3781, 0.667_8672, 0.548_6515, 0.9220_2145, 0.6783_1135, 0.5625_3487, 0.924_1694, 0.755_1478, 0.645_9706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3E-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3E-3 @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> int: super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self , A_ , A_="cpu" , A_=torch.floataa , A_=0 ) -> Optional[int]: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase =np.random.RandomState(A_ ).standard_normal((1, 4, 64, 64) ) __UpperCamelCase =torch.from_numpy(A_ ).to(device=A_ , dtype=A_ ) __UpperCamelCase ={ 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 50, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _a ( self ) -> List[str]: __UpperCamelCase =StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d' ).to(A_ ) ldmad_pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_inputs(A_ ) __UpperCamelCase =ldmad_pipe(**A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =0.49_5586 __UpperCamelCase =0.3379_5515 __UpperCamelCase =112.4_8518 __UpperCamelCase =98.48_9746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3 def _a ( self ) -> Optional[Any]: __UpperCamelCase =StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c' ).to(A_ ) ldmad_pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_inputs(A_ ) __UpperCamelCase =ldmad_pipe(**A_ ) __UpperCamelCase , __UpperCamelCase =output.rgb, output.depth __UpperCamelCase =0.419_4127 __UpperCamelCase =0.3537_5586 __UpperCamelCase =0.563_8502 __UpperCamelCase =0.3468_6103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration _A = HfArgumentParser(InitializationArguments) _A = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization _A = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks _A = { 'vocab_size': len(tokenizer), 'scale_attn_by_inverse_layer_idx': True, 'reorder_and_upcast_attn': True, } # Load model config (GPT-2 large in this case) _A = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config _A = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , A_ ) -> Any: __UpperCamelCase =parent def _a ( self ) -> Optional[Any]: return {} def _UpperCAmelCase ( ): __UpperCamelCase ='<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR="FFFFFF">\n <HR>\n <a href="http://google.com">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style="color:#0000FF">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>' __UpperCamelCase ='\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n ' return [html_string_a, html_string_a] @require_bsa class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : int = MarkupLMFeatureExtractor if is_bsa_available() else None def _a ( self ) -> str: __UpperCamelCase =MarkupLMFeatureExtractionTester(self ) @property def _a ( self ) -> Union[str, Any]: return self.feature_extract_tester.prepare_feat_extract_dict() def _a ( self ) -> Tuple: # Initialize feature_extractor __UpperCamelCase =self.feature_extraction_class() # Test not batched input __UpperCamelCase =get_html_strings()[0] __UpperCamelCase =feature_extractor(A_ ) # fmt: off __UpperCamelCase =[['sample document', 'Goog', 'This is one header', 'This is a another Header', 'Travel from', 'SFO to JFK', 'on May 2, 2015 at 2:00 pm. For details go to confirm.com', 'Traveler', 'name', 'is', 'John Doe']] __UpperCamelCase =[['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']] # fmt: on self.assertEqual(encoding.nodes , A_ ) self.assertEqual(encoding.xpaths , A_ ) # Test batched __UpperCamelCase =get_html_strings() __UpperCamelCase =feature_extractor(A_ ) # fmt: off __UpperCamelCase =expected_nodes + [['My First Heading', 'My first paragraph.']] __UpperCamelCase =expected_xpaths + [['/html/body/h1', '/html/body/p']] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , A_ ) self.assertEqual(encoding.xpaths , A_ )
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import doctest from collections import deque import numpy as np class UpperCAmelCase__ : """simple docstring""" def __init__( self ) -> None: __UpperCamelCase =[2, 1, 2, -1] __UpperCamelCase =[1, 2, 3, 4] def _a ( self ) -> list[float]: __UpperCamelCase =len(self.first_signal ) __UpperCamelCase =len(self.second_signal ) __UpperCamelCase =max(A_ , A_ ) # create a zero matrix of max_length x max_length __UpperCamelCase =[[0] * max_length for i in range(A_ )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(A_ ): __UpperCamelCase =deque(self.second_signal ) rotated_signal.rotate(A_ ) for j, item in enumerate(A_ ): matrix[i][j] += item # multiply the matrix with the first signal __UpperCamelCase =np.matmul(np.transpose(A_ ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(A_ , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =20 * np.logaa(SCREAMING_SNAKE_CASE__ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds __UpperCamelCase =get_bounds(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE__ , -2 * pi ) ) plt.show()
62
1
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ = None , A_ = None , A_ = False , A_ = False , A_ = None , A_ = None , **A_ , ) -> List[str]: super().__init__( features=A_ , cache_dir=A_ , keep_in_memory=A_ , streaming=A_ , num_proc=A_ , **A_ , ) __UpperCamelCase =Generator( cache_dir=A_ , features=A_ , generator=A_ , gen_kwargs=A_ , **A_ , ) def _a ( self ) -> Any: # Build iterable dataset if self.streaming: __UpperCamelCase =self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None self.builder.download_and_prepare( download_config=A_ , download_mode=A_ , verification_mode=A_ , base_path=A_ , num_proc=self.num_proc , ) __UpperCamelCase =self.builder.as_dataset( split='train' , verification_mode=A_ , in_memory=self.keep_in_memory ) return dataset
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values 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 ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_=13 , A_=30 , A_=2 , A_=3 , A_=True , A_=True , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=10 , A_=0.02 , A_=3 , A_=None , A_=2 , ) -> List[str]: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =is_training __UpperCamelCase =use_labels __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =type_sequence_label_size __UpperCamelCase =initializer_range __UpperCamelCase =scope __UpperCamelCase =encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __UpperCamelCase =(image_size // patch_size) ** 2 __UpperCamelCase =num_patches + 2 def _a ( self ) -> Dict: __UpperCamelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase =self.get_config() return config, pixel_values, labels def _a ( self ) -> Optional[Any]: return DeiTConfig( 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=A_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a ( self , A_ , A_ , A_ ) -> Union[str, Any]: __UpperCamelCase =DeiTModel(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ ) -> Optional[int]: __UpperCamelCase =DeiTForMaskedImageModeling(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __UpperCamelCase =1 __UpperCamelCase =DeiTForMaskedImageModeling(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , A_ , A_ , A_ ) -> Any: __UpperCamelCase =self.type_sequence_label_size __UpperCamelCase =DeiTForImageClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __UpperCamelCase =1 __UpperCamelCase =DeiTForImageClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase =model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ) -> Any: __UpperCamelCase =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) =config_and_inputs __UpperCamelCase ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase__ ( A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) UpperCAmelCase__ : Tuple = ( { "feature-extraction": DeiTModel, "image-classification": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : str = False UpperCAmelCase__ : Dict = False def _a ( self ) -> Any: __UpperCamelCase =DeiTModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def _a ( self ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def _a ( self ) -> int: pass def _a ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase =model_class(A_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCamelCase =model.get_output_embeddings() self.assertTrue(x is None or isinstance(A_ , nn.Linear ) ) def _a ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase =[*signature.parameters.keys()] __UpperCamelCase =['pixel_values'] self.assertListEqual(arg_names[:1] , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A_ ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) def _a ( self , A_ , A_ , A_=False ) -> str: __UpperCamelCase =super()._prepare_for_class(A_ , A_ , return_labels=A_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _a ( self ) -> Optional[Any]: if not self.model_tester.is_training: return __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(A_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __UpperCamelCase =model_class(A_ ) model.to(A_ ) model.train() __UpperCamelCase =self._prepare_for_class(A_ , A_ , return_labels=A_ ) __UpperCamelCase =model(**A_ ).loss loss.backward() def _a ( self ) -> int: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __UpperCamelCase =False __UpperCamelCase =True for model_class in self.all_model_classes: if model_class in get_values(A_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __UpperCamelCase =model_class(A_ ) model.gradient_checkpointing_enable() model.to(A_ ) model.train() __UpperCamelCase =self._prepare_for_class(A_ , A_ , return_labels=A_ ) __UpperCamelCase =model(**A_ ).loss loss.backward() def _a ( self ) -> Optional[Any]: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =[ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(A_ ), *get_values(A_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f'Testing {model_class} with {problem_type["title"]}' ): __UpperCamelCase =problem_type['title'] __UpperCamelCase =problem_type['num_labels'] __UpperCamelCase =model_class(A_ ) model.to(A_ ) model.train() __UpperCamelCase =self._prepare_for_class(A_ , A_ , return_labels=A_ ) if problem_type["num_labels"] > 1: __UpperCamelCase =inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) __UpperCamelCase =inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=A_ ) as warning_list: __UpperCamelCase =model(**A_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f'Something is going wrong in the regression problem: intercepted {w.message}' ) loss.backward() @slow def _a ( self ) -> Tuple: for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase =DeiTModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _UpperCAmelCase ( ): __UpperCamelCase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self ) -> Tuple: return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def _a ( self ) -> Optional[Any]: __UpperCamelCase =DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( A_ ) __UpperCamelCase =self.default_image_processor __UpperCamelCase =prepare_img() __UpperCamelCase =image_processor(images=A_ , return_tensors='pt' ).to(A_ ) # forward pass with torch.no_grad(): __UpperCamelCase =model(**A_ ) # verify the logits __UpperCamelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , A_ ) __UpperCamelCase =torch.tensor([-1.0266, 0.1912, -1.2861] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def _a ( self ) -> Tuple: __UpperCamelCase =DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) __UpperCamelCase =self.default_image_processor __UpperCamelCase =prepare_img() __UpperCamelCase =image_processor(images=A_ , return_tensors='pt' ) __UpperCamelCase =inputs.pixel_values.to(A_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __UpperCamelCase =model(A_ )
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( 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_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =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.' )
62
1
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_logger(__name__) _A = { 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } _A = { 'b0': { 'hidden_dim': 1280, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 224, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 1280, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 240, 'dropout_rate': 0.2, 'dw_padding': [16], }, 'b2': { 'hidden_dim': 1408, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 260, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 16], }, 'b3': { 'hidden_dim': 1536, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 300, 'dropout_rate': 0.3, 'dw_padding': [5, 18], }, 'b4': { 'hidden_dim': 1792, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 380, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 2048, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 456, 'dropout_rate': 0.4, 'dw_padding': [13, 27], }, 'b6': { 'hidden_dim': 2304, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 528, 'dropout_rate': 0.5, 'dw_padding': [31], }, 'b7': { 'hidden_dim': 2560, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 600, 'dropout_rate': 0.5, 'dw_padding': [18], }, } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =EfficientNetConfig() __UpperCamelCase =CONFIG_MAP[model_name]['hidden_dim'] __UpperCamelCase =CONFIG_MAP[model_name]['width_coef'] __UpperCamelCase =CONFIG_MAP[model_name]['depth_coef'] __UpperCamelCase =CONFIG_MAP[model_name]['image_size'] __UpperCamelCase =CONFIG_MAP[model_name]['dropout_rate'] __UpperCamelCase =CONFIG_MAP[model_name]['dw_padding'] __UpperCamelCase ='huggingface/label-files' __UpperCamelCase ='imagenet-1k-id2label.json' __UpperCamelCase =10_00 __UpperCamelCase =json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) ) __UpperCamelCase ={int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} __UpperCamelCase =idalabel __UpperCamelCase ={v: k for k, v in idalabel.items()} return config def _UpperCAmelCase ( ): __UpperCamelCase ='http://images.cocodataset.org/val2017/000000039769.jpg' __UpperCamelCase =Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __UpperCamelCase =CONFIG_MAP[model_name]['image_size'] __UpperCamelCase =EfficientNetImageProcessor( size={'height': size, 'width': size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.47853944, 0.4732864, 0.47434163] , do_center_crop=SCREAMING_SNAKE_CASE__ , ) return preprocessor def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =[v.split('_' )[0].split('block' )[1] for v in original_param_names if v.startswith('block' )] __UpperCamelCase =sorted(set(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase ={b: str(SCREAMING_SNAKE_CASE__ ) for b, i in zip(SCREAMING_SNAKE_CASE__ , range(SCREAMING_SNAKE_CASE__ ) )} __UpperCamelCase =[] rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight') ) rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight') ) rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias') ) rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean') ) rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var') ) for b in block_names: __UpperCamelCase =block_name_mapping[b] rename_keys.append((F'block{b}_expand_conv/kernel:0', F'encoder.blocks.{hf_b}.expansion.expand_conv.weight') ) rename_keys.append((F'block{b}_expand_bn/gamma:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.weight') ) rename_keys.append((F'block{b}_expand_bn/beta:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.bias') ) rename_keys.append( (F'block{b}_expand_bn/moving_mean:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_mean') ) rename_keys.append( (F'block{b}_expand_bn/moving_variance:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_var') ) rename_keys.append( (F'block{b}_dwconv/depthwise_kernel:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight') ) rename_keys.append((F'block{b}_bn/gamma:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight') ) rename_keys.append((F'block{b}_bn/beta:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias') ) rename_keys.append( (F'block{b}_bn/moving_mean:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean') ) rename_keys.append( (F'block{b}_bn/moving_variance:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var') ) rename_keys.append((F'block{b}_se_reduce/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.weight') ) rename_keys.append((F'block{b}_se_reduce/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.bias') ) rename_keys.append((F'block{b}_se_expand/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.weight') ) rename_keys.append((F'block{b}_se_expand/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.bias') ) rename_keys.append( (F'block{b}_project_conv/kernel:0', F'encoder.blocks.{hf_b}.projection.project_conv.weight') ) rename_keys.append((F'block{b}_project_bn/gamma:0', F'encoder.blocks.{hf_b}.projection.project_bn.weight') ) rename_keys.append((F'block{b}_project_bn/beta:0', F'encoder.blocks.{hf_b}.projection.project_bn.bias') ) rename_keys.append( (F'block{b}_project_bn/moving_mean:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_mean') ) rename_keys.append( (F'block{b}_project_bn/moving_variance:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_var') ) rename_keys.append(('top_conv/kernel:0', 'encoder.top_conv.weight') ) rename_keys.append(('top_bn/gamma:0', 'encoder.top_bn.weight') ) rename_keys.append(('top_bn/beta:0', 'encoder.top_bn.bias') ) rename_keys.append(('top_bn/moving_mean:0', 'encoder.top_bn.running_mean') ) rename_keys.append(('top_bn/moving_variance:0', 'encoder.top_bn.running_var') ) __UpperCamelCase ={} for item in rename_keys: if item[0] in original_param_names: __UpperCamelCase ='efficientnet.' + item[1] __UpperCamelCase ='classifier.weight' __UpperCamelCase ='classifier.bias' return key_mapping def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ): for key, value in tf_params.items(): if "normalization" in key: continue __UpperCamelCase =key_mapping[key] if "_conv" in key and "kernel" in key: __UpperCamelCase =torch.from_numpy(SCREAMING_SNAKE_CASE__ ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: __UpperCamelCase =torch.from_numpy(SCREAMING_SNAKE_CASE__ ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: __UpperCamelCase =torch.from_numpy(np.transpose(SCREAMING_SNAKE_CASE__ ) ) else: __UpperCamelCase =torch.from_numpy(SCREAMING_SNAKE_CASE__ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __UpperCamelCase =model_classes[model_name]( include_top=SCREAMING_SNAKE_CASE__ , weights='imagenet' , input_tensor=SCREAMING_SNAKE_CASE__ , input_shape=SCREAMING_SNAKE_CASE__ , pooling=SCREAMING_SNAKE_CASE__ , classes=10_00 , classifier_activation='softmax' , ) __UpperCamelCase =original_model.trainable_variables __UpperCamelCase =original_model.non_trainable_variables __UpperCamelCase ={param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: __UpperCamelCase =param.numpy() __UpperCamelCase =list(tf_params.keys() ) # Load HuggingFace model __UpperCamelCase =get_efficientnet_config(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =EfficientNetForImageClassification(SCREAMING_SNAKE_CASE__ ).eval() __UpperCamelCase =hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('Converting parameters...' ) __UpperCamelCase =rename_keys(SCREAMING_SNAKE_CASE__ ) replace_params(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Initialize preprocessor and preprocess input image __UpperCamelCase =convert_image_processor(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =preprocessor(images=prepare_img() , return_tensors='pt' ) # HF model inference hf_model.eval() with torch.no_grad(): __UpperCamelCase =hf_model(**SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =outputs.logits.detach().numpy() # Original model inference __UpperCamelCase =False __UpperCamelCase =CONFIG_MAP[model_name]['image_size'] __UpperCamelCase =prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) __UpperCamelCase =image.img_to_array(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=0 ) __UpperCamelCase =original_model.predict(SCREAMING_SNAKE_CASE__ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ), "The predicted logits are not the same." print('Model outputs match!' ) if save_model: # Create folder to save model if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): os.mkdir(SCREAMING_SNAKE_CASE__ ) # Save converted model and image processor hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) preprocessor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: # Push model and image processor to hub print(F'Pushing converted {model_name} to the hub...' ) __UpperCamelCase =F'efficientnet-{model_name}' preprocessor.push_to_hub(SCREAMING_SNAKE_CASE__ ) hf_model.push_to_hub(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') _A = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 1_00 ): __UpperCamelCase =n * (n + 1) * (2 * n + 1) / 6 __UpperCamelCase =(n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _A = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _A = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _A = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =len([g for position, g in enumerate(SCREAMING_SNAKE_CASE__ ) if g == main_target[position]] ) return (item, float(SCREAMING_SNAKE_CASE__ )) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) __UpperCamelCase =parent_a[:random_slice] + parent_a[random_slice:] __UpperCamelCase =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ): __UpperCamelCase =list(SCREAMING_SNAKE_CASE__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: __UpperCamelCase =random.choice(SCREAMING_SNAKE_CASE__ ) return "".join(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : tuple[str, float] , SCREAMING_SNAKE_CASE__ : list[tuple[str, float]] , SCREAMING_SNAKE_CASE__ : list[str] , ): __UpperCamelCase =[] # Generate more children proportionally to the fitness score. __UpperCamelCase =int(parent_a[1] * 1_00 ) + 1 __UpperCamelCase =10 if child_n >= 10 else child_n for _ in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =population_score[random.randint(0 , SCREAMING_SNAKE_CASE__ )][0] __UpperCamelCase , __UpperCamelCase =crossover(parent_a[0] , SCREAMING_SNAKE_CASE__ ) # Append new string to the population list. pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) pop.append(mutate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return pop def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] , SCREAMING_SNAKE_CASE__ : bool = True ): # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: __UpperCamelCase =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Verify that the target contains no genes besides the ones inside genes variable. __UpperCamelCase =sorted({c for c in target if c not in genes} ) if not_in_genes_list: __UpperCamelCase =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(SCREAMING_SNAKE_CASE__ ) # Generate random starting population. __UpperCamelCase =[] for _ in range(SCREAMING_SNAKE_CASE__ ): population.append(''.join([random.choice(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ) ) # Just some logs to know what the algorithms is doing. __UpperCamelCase , __UpperCamelCase =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(SCREAMING_SNAKE_CASE__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. __UpperCamelCase =[evaluate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for item in population] # Check if there is a matching evolution. __UpperCamelCase =sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[1] , reverse=SCREAMING_SNAKE_CASE__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. __UpperCamelCase =population[: int(N_POPULATION / 3 )] population.clear() population.extend(SCREAMING_SNAKE_CASE__ ) # Normalize population score to be between 0 and 1. __UpperCamelCase =[ (item, score / len(SCREAMING_SNAKE_CASE__ )) for item, score in population_score ] # This is selection for i in range(SCREAMING_SNAKE_CASE__ ): population.extend(select(population_score[int(SCREAMING_SNAKE_CASE__ )] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(SCREAMING_SNAKE_CASE__ ) > N_POPULATION: break if __name__ == "__main__": _A = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) _A = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) _A , _A , _A = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _A = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['DeiTFeatureExtractor'] _A = ['DeiTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DeiTForImageClassification', 'DeiTForImageClassificationWithTeacher', 'DeiTForMaskedImageModeling', 'DeiTModel', 'DeiTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDeiTForImageClassification', 'TFDeiTForImageClassificationWithTeacher', 'TFDeiTForMaskedImageModeling', 'TFDeiTModel', 'TFDeiTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[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] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
import math import unittest from transformers import BioGptConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=False , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ) -> Optional[int]: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =seq_length __UpperCamelCase =is_training __UpperCamelCase =use_input_mask __UpperCamelCase =use_token_type_ids __UpperCamelCase =use_labels __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =type_vocab_size __UpperCamelCase =type_sequence_label_size __UpperCamelCase =initializer_range __UpperCamelCase =num_labels __UpperCamelCase =num_choices __UpperCamelCase =scope def _a ( self ) -> Dict: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase =None if self.use_input_mask: __UpperCamelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase =None if self.use_token_type_ids: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase =ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> Optional[Any]: return BioGptConfig( 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=A_ , initializer_range=self.initializer_range , ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> List[str]: __UpperCamelCase =BioGptModel(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ ) __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> Union[str, Any]: __UpperCamelCase =BioGptForCausalLM(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , *A_ ) -> str: __UpperCamelCase =BioGptModel(config=A_ ) model.to(A_ ) model.eval() # create attention mask __UpperCamelCase =torch.ones(input_ids.shape , dtype=torch.long , device=A_ ) __UpperCamelCase =self.seq_length // 2 __UpperCamelCase =0 # first forward pass __UpperCamelCase , __UpperCamelCase =model(A_ , attention_mask=A_ ).to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCamelCase =ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __UpperCamelCase =ids_tensor((1,) , A_ ).item() + 1 __UpperCamelCase =ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __UpperCamelCase =random_other_next_tokens # append to next input_ids and attn_mask __UpperCamelCase =torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCamelCase =torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=A_ )] , dim=1 , ) # get two different outputs __UpperCamelCase =model(A_ , attention_mask=A_ )['last_hidden_state'] __UpperCamelCase =model(A_ , past_key_values=A_ , attention_mask=A_ )['last_hidden_state'] # select random slice __UpperCamelCase =ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCamelCase =output_from_no_past[:, -1, random_slice_idx].detach() __UpperCamelCase =output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A_ , A_ , atol=1E-3 ) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , *A_ ) -> Tuple: __UpperCamelCase =BioGptModel(config=A_ ).to(A_ ).eval() __UpperCamelCase =torch.ones(input_ids.shape , dtype=torch.long , device=A_ ) # first forward pass __UpperCamelCase =model(A_ , attention_mask=A_ , use_cache=A_ ) __UpperCamelCase , __UpperCamelCase =outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __UpperCamelCase =ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase =ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __UpperCamelCase =torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCamelCase =torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __UpperCamelCase =model(A_ , attention_mask=A_ )['last_hidden_state'] __UpperCamelCase =model(A_ , attention_mask=A_ , past_key_values=A_ )[ 'last_hidden_state' ] # select random slice __UpperCamelCase =ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCamelCase =output_from_no_past[:, -3:, random_slice_idx].detach() __UpperCamelCase =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A_ , A_ , atol=1E-3 ) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , *A_ , A_=False ) -> List[str]: __UpperCamelCase =BioGptForCausalLM(A_ ) model.to(A_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __UpperCamelCase =model(A_ , labels=A_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _a ( self , A_ , *A_ ) -> Tuple: __UpperCamelCase =BioGptModel(A_ ) __UpperCamelCase =model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _a ( self , A_ , A_ , A_ , A_ , A_ , *A_ ) -> Tuple: __UpperCamelCase =self.num_labels __UpperCamelCase =BioGptForTokenClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , token_type_ids=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self ) -> int: __UpperCamelCase =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) =config_and_inputs __UpperCamelCase ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase__ ( A_ , A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) UpperCAmelCase__ : int = (BioGptForCausalLM,) if is_torch_available() else () UpperCAmelCase__ : Any = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ : Tuple = False def _a ( self ) -> Dict: __UpperCamelCase =BioGptModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , hidden_size=37 ) def _a ( self ) -> Optional[int]: self.config_tester.run_common_tests() def _a ( self ) -> str: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCamelCase =type self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> int: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*A_ , gradient_checkpointing=A_ ) def _a ( self ) -> Any: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*A_ ) def _a ( self ) -> List[str]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*A_ ) def _a ( self ) -> Any: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*A_ ) @slow def _a ( self ) -> Union[str, Any]: __UpperCamelCase =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(A_ ) __UpperCamelCase =BioGptTokenizer.from_pretrained('microsoft/biogpt' ) __UpperCamelCase ='left' # Define PAD Token = EOS Token = 50256 __UpperCamelCase =tokenizer.eos_token __UpperCamelCase =model.config.eos_token_id # use different length sentences to test batching __UpperCamelCase =[ 'Hello, my dog is a little', 'Today, I', ] __UpperCamelCase =tokenizer(A_ , return_tensors='pt' , padding=A_ ) __UpperCamelCase =inputs['input_ids'].to(A_ ) __UpperCamelCase =model.generate( input_ids=A_ , attention_mask=inputs['attention_mask'].to(A_ ) , ) __UpperCamelCase =tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(A_ ) __UpperCamelCase =model.generate(input_ids=A_ ) __UpperCamelCase =inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() __UpperCamelCase =tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(A_ ) __UpperCamelCase =model.generate(input_ids=A_ , max_length=model.config.max_length - num_paddings ) __UpperCamelCase =tokenizer.batch_decode(A_ , skip_special_tokens=A_ ) __UpperCamelCase =tokenizer.decode(output_non_padded[0] , skip_special_tokens=A_ ) __UpperCamelCase =tokenizer.decode(output_padded[0] , skip_special_tokens=A_ ) __UpperCamelCase =[ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(A_ , A_ ) self.assertListEqual(A_ , [non_padded_sentence, padded_sentence] ) @slow def _a ( self ) -> List[Any]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase =BioGptModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCamelCase =BioGptForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> Any: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase ='multi_label_classification' __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __UpperCamelCase =BioGptForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def _a ( self ) -> Tuple: __UpperCamelCase =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) __UpperCamelCase =torch.tensor([[2, 4805, 9, 656, 21]] ) __UpperCamelCase =model(A_ )[0] __UpperCamelCase =42384 __UpperCamelCase =torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , A_ ) __UpperCamelCase =torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , A_ , atol=1E-4 ) ) @slow def _a ( self ) -> Optional[int]: __UpperCamelCase =BioGptTokenizer.from_pretrained('microsoft/biogpt' ) __UpperCamelCase =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(A_ ) torch.manual_seed(0 ) __UpperCamelCase =tokenizer('COVID-19 is' , return_tensors='pt' ).to(A_ ) __UpperCamelCase =model.generate( **A_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=A_ , ) __UpperCamelCase =tokenizer.decode(output_ids[0] , skip_special_tokens=A_ ) __UpperCamelCase =( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(A_ , A_ )
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time _A = Lock() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(SCREAMING_SNAKE_CASE__ ) process_lock.release() # receive your right neighbor's value process_lock.acquire() __UpperCamelCase =rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(SCREAMING_SNAKE_CASE__ ) process_lock.release() # receive your left neighbor's value process_lock.acquire() __UpperCamelCase =lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right __UpperCamelCase =max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # after all swaps are performed, send the values back to main result_pipe[1].send(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =[] __UpperCamelCase =[] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop __UpperCamelCase =Pipe() __UpperCamelCase =Pipe() process_array_.append( Process( target=SCREAMING_SNAKE_CASE__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) __UpperCamelCase =temp_rs __UpperCamelCase =temp_rr for i in range(1 , len(SCREAMING_SNAKE_CASE__ ) - 1 ): __UpperCamelCase =Pipe() __UpperCamelCase =Pipe() process_array_.append( Process( target=SCREAMING_SNAKE_CASE__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) __UpperCamelCase =temp_rs __UpperCamelCase =temp_rr process_array_.append( Process( target=SCREAMING_SNAKE_CASE__ , args=( len(SCREAMING_SNAKE_CASE__ ) - 1, arr[len(SCREAMING_SNAKE_CASE__ ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(SCREAMING_SNAKE_CASE__ ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =result_pipe[p][0].recv() process_array_[p].join() return arr def _UpperCAmelCase ( ): __UpperCamelCase =list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =odd_even_transposition(SCREAMING_SNAKE_CASE__ ) print('Sorted List\n' ) print(*SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
62
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ) -> PIL.Image.Image: __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(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =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.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
from __future__ import annotations import math def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =u for i in range(1 , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =temp * (u - i) return temp def _UpperCAmelCase ( ): __UpperCamelCase =int(input('enter the numbers of values: ' ) ) __UpperCamelCase =[] for _ in range(SCREAMING_SNAKE_CASE__ ): y.append([] ) for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): y[i].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =0 print('enter the values of parameters in a list: ' ) __UpperCamelCase =list(map(SCREAMING_SNAKE_CASE__ , input().split() ) ) print('enter the values of corresponding parameters: ' ) for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =float(input() ) __UpperCamelCase =int(input('enter the value to interpolate: ' ) ) __UpperCamelCase =(value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , SCREAMING_SNAKE_CASE__ ): for j in range(n - i ): __UpperCamelCase =y[j + 1][i - 1] - y[j][i - 1] __UpperCamelCase =y[0][0] for i in range(1 , SCREAMING_SNAKE_CASE__ ): summ += (ucal(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) * y[0][i]) / math.factorial(SCREAMING_SNAKE_CASE__ ) print(F'the value at {value} is {summ}' ) if __name__ == "__main__": main()
62
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 _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
def _UpperCAmelCase ( ): __UpperCamelCase =[] __UpperCamelCase =1 while len(SCREAMING_SNAKE_CASE__ ) < 1E6: constant.append(str(SCREAMING_SNAKE_CASE__ ) ) i += 1 __UpperCamelCase =''.join(SCREAMING_SNAKE_CASE__ ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[9_99] ) * int(constant[99_99] ) * int(constant[9_99_99] ) * int(constant[99_99_99] ) ) if __name__ == "__main__": print(solution())
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _UpperCAmelCase ( *SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =list(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Exception ): __UpperCamelCase =[ 'CUDA out of memory.', # CUDA OOM 'cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.', # CUDNN SNAFU 'DefaultCPUAllocator: can\'t allocate memory', # CPU OOM ] if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : callable = None , SCREAMING_SNAKE_CASE__ : int = 1_28 ): if function is None: return functools.partial(SCREAMING_SNAKE_CASE__ , starting_batch_size=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =starting_batch_size def decorator(*SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() __UpperCamelCase =list(inspect.signature(SCREAMING_SNAKE_CASE__ ).parameters.keys() ) # Guard against user error if len(SCREAMING_SNAKE_CASE__ ) < (len(SCREAMING_SNAKE_CASE__ ) + 1): __UpperCamelCase =', '.join([F'{arg}={value}' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F'Batch size was passed into `{function.__name__}` as the first argument when called.' F'Remove this as the decorator already does so: `{function.__name__}({arg_str})`' ) while True: if batch_size == 0: raise RuntimeError('No executable batch size found, reached zero.' ) try: return function(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) except Exception as e: if should_reduce_batch_size(SCREAMING_SNAKE_CASE__ ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
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 _A = logging.get_logger(__name__) _A = { '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__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "bart" UpperCAmelCase__ : List[Any] = ["past_key_values"] UpperCAmelCase__ : Optional[int] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50265 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=3 , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , **A_ , ) -> Optional[int]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =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_ ): __UpperCamelCase =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__ ( A_ ): """simple docstring""" @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task in ["default", "seq2seq-lm"]: __UpperCamelCase =OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: __UpperCamelCase ={0: 'batch'} __UpperCamelCase ={0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __UpperCamelCase ={0: 'batch', 1: 'decoder_sequence'} __UpperCamelCase ={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. __UpperCamelCase =OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: __UpperCamelCase , __UpperCamelCase =self.num_layers for i in range(A_ ): __UpperCamelCase ={0: 'batch', 2: 'past_sequence + sequence'} __UpperCamelCase ={0: 'batch', 2: 'past_sequence + sequence'} else: __UpperCamelCase =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 _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task in ["default", "seq2seq-lm"]: __UpperCamelCase =super().outputs else: __UpperCamelCase =super(A_ , self ).outputs if self.use_past: __UpperCamelCase , __UpperCamelCase =self.num_layers for i in range(A_ ): __UpperCamelCase ={0: 'batch', 2: 'past_sequence + sequence'} __UpperCamelCase ={0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def _a ( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ) -> Mapping[str, Any]: __UpperCamelCase =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) # Generate decoder inputs __UpperCamelCase =seq_length if not self.use_past else 1 __UpperCamelCase =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( A_ , A_ , A_ , A_ , A_ ) __UpperCamelCase ={f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} __UpperCamelCase =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 __UpperCamelCase , __UpperCamelCase =common_inputs['input_ids'].shape __UpperCamelCase =common_inputs['decoder_input_ids'].shape[1] __UpperCamelCase , __UpperCamelCase =self.num_attention_heads __UpperCamelCase =( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __UpperCamelCase =decoder_seq_length + 3 __UpperCamelCase =( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __UpperCamelCase =torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(A_ , A_ )] , dim=1 ) __UpperCamelCase =[] # If the number of encoder and decoder layers are present in the model configuration, both are considered __UpperCamelCase , __UpperCamelCase =self.num_layers __UpperCamelCase =min(A_ , A_ ) __UpperCamelCase =max(A_ , A_ ) - min_num_layers __UpperCamelCase ='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. __UpperCamelCase =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 _a ( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ) -> Mapping[str, Any]: __UpperCamelCase =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 __UpperCamelCase , __UpperCamelCase =common_inputs['input_ids'].shape # Not using the same length for past_key_values __UpperCamelCase =seqlen + 2 __UpperCamelCase , __UpperCamelCase =self.num_layers __UpperCamelCase , __UpperCamelCase =self.num_attention_heads __UpperCamelCase =( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __UpperCamelCase =common_inputs['attention_mask'].dtype __UpperCamelCase =torch.cat( [common_inputs['attention_mask'], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 ) __UpperCamelCase =[ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(A_ ) ] return common_inputs def _a ( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ) -> Mapping[str, Any]: # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __UpperCamelCase =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 __UpperCamelCase =tokenizer.num_special_tokens_to_add(A_ ) __UpperCamelCase =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 __UpperCamelCase =[' '.join([tokenizer.unk_token] ) * seq_length] * batch_size __UpperCamelCase =dict(tokenizer(A_ , return_tensors=A_ ) ) return common_inputs def _a ( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ) -> Mapping[str, Any]: if self.task in ["default", "seq2seq-lm"]: __UpperCamelCase =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": __UpperCamelCase =self._generate_dummy_inputs_for_causal_lm( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) else: __UpperCamelCase =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 _a ( self , A_ , A_ , A_ , A_ ) -> str: if self.task in ["default", "seq2seq-lm"]: __UpperCamelCase =super()._flatten_past_key_values_(A_ , A_ , A_ , A_ ) else: __UpperCamelCase =super(A_ , self )._flatten_past_key_values_( A_ , A_ , A_ , A_ )
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar _A = TypeVar('KEY') _A = TypeVar('VAL') @dataclass(frozen=A_ , slots=A_ ) class UpperCAmelCase__ ( Generic[KEY, VAL] ): """simple docstring""" UpperCAmelCase__ : KEY UpperCAmelCase__ : VAL class UpperCAmelCase__ ( _Item ): """simple docstring""" def __init__( self ) -> None: super().__init__(A_ , A_ ) def __bool__( self ) -> bool: return False _A = _DeletedItem() class UpperCAmelCase__ ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self , A_ = 8 , A_ = 0.75 ) -> None: __UpperCamelCase =initial_block_size __UpperCamelCase =[None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __UpperCamelCase =capacity_factor __UpperCamelCase =0 def _a ( self , A_ ) -> int: return hash(A_ ) % len(self._buckets ) def _a ( self , A_ ) -> int: return (ind + 1) % len(self._buckets ) def _a ( self , A_ , A_ , A_ ) -> bool: __UpperCamelCase =self._buckets[ind] if not stored: __UpperCamelCase =_Item(A_ , A_ ) self._len += 1 return True elif stored.key == key: __UpperCamelCase =_Item(A_ , A_ ) return True else: return False def _a ( self ) -> bool: __UpperCamelCase =len(self._buckets ) * self._capacity_factor return len(self ) >= int(A_ ) def _a ( self ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False __UpperCamelCase =len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def _a ( self , A_ ) -> None: __UpperCamelCase =self._buckets __UpperCamelCase =[None] * new_size __UpperCamelCase =0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def _a ( self ) -> None: self._resize(len(self._buckets ) * 2 ) def _a ( self ) -> None: self._resize(len(self._buckets ) // 2 ) def _a ( self , A_ ) -> Iterator[int]: __UpperCamelCase =self._get_bucket_index(A_ ) for _ in range(len(self._buckets ) ): yield ind __UpperCamelCase =self._get_next_ind(A_ ) def _a ( self , A_ , A_ ) -> None: for ind in self._iterate_buckets(A_ ): if self._try_set(A_ , A_ , A_ ): break def __setitem__( self , A_ , A_ ) -> None: if self._is_full(): self._size_up() self._add_item(A_ , A_ ) def __delitem__( self , A_ ) -> None: for ind in self._iterate_buckets(A_ ): __UpperCamelCase =self._buckets[ind] if item is None: raise KeyError(A_ ) if item is _deleted: continue if item.key == key: __UpperCamelCase =_deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , A_ ) -> VAL: for ind in self._iterate_buckets(A_ ): __UpperCamelCase =self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(A_ ) def __len__( self ) -> int: return self._len def __iter__( self ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self ) -> str: __UpperCamelCase =' ,'.join( f'{item.key}: {item.val}' for item in self._buckets if item ) return f'HashMap({val_string})'
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": _A = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') _A = f"""https://www.google.com/search?q={query}&num=100""" _A = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: _A = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: _A = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging _A = logging.get_logger(__name__) logging.set_verbosity_info() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): if "xprophetnet" in prophetnet_checkpoint_path: __UpperCamelCase =XLMProphetNetForConditionalGenerationOld.from_pretrained(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =XLMProphetNetForConditionalGeneration.from_pretrained( SCREAMING_SNAKE_CASE__ , output_loading_info=SCREAMING_SNAKE_CASE__ ) else: __UpperCamelCase =ProphetNetForConditionalGenerationOld.from_pretrained(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =ProphetNetForConditionalGeneration.from_pretrained( SCREAMING_SNAKE_CASE__ , output_loading_info=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =['key_proj', 'value_proj', 'query_proj'] __UpperCamelCase ={ 'self_attn': 'ngram_self_attn', 'cross_attn': 'encoder_attn', 'cross_attn_layer_norm': 'encoder_attn_layer_norm', 'feed_forward_layer_norm': 'final_layer_norm', 'feed_forward': '', 'intermediate': 'fc1', 'output': 'fc2', 'key_proj': 'k_proj', 'query_proj': 'q_proj', 'value_proj': 'v_proj', 'word_embeddings': 'embed_tokens', 'embeddings_layer_norm': 'emb_layer_norm', 'relative_pos_embeddings': 'relative_linear', 'ngram_embeddings': 'ngram_input_embed', 'position_embeddings': 'embed_positions', } for key in loading_info["missing_keys"]: __UpperCamelCase =key.split('.' ) if attributes[0] == "lm_head": __UpperCamelCase =prophet __UpperCamelCase =prophet_old else: __UpperCamelCase =prophet.prophetnet __UpperCamelCase =prophet_old.model __UpperCamelCase =False for attribute in attributes: if attribute in mapping: __UpperCamelCase =mapping[attribute] if not hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) > 0: __UpperCamelCase =attribute elif hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" __UpperCamelCase =old_model.weight logger.info(F'{attribute} is initialized.' ) __UpperCamelCase =True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" __UpperCamelCase =old_model.bias logger.info(F'{attribute} is initialized' ) __UpperCamelCase =True break elif attribute in special_keys and hasattr(SCREAMING_SNAKE_CASE__ , 'in_proj_weight' ): __UpperCamelCase =old_model.in_proj_weight.shape[0] // 3 __UpperCamelCase =getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": __UpperCamelCase =nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) __UpperCamelCase =nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": __UpperCamelCase =nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) __UpperCamelCase =nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": __UpperCamelCase =nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) __UpperCamelCase =nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) __UpperCamelCase =True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_12, "We want 512 position_embeddings." __UpperCamelCase =nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) __UpperCamelCase =True break if attribute.isdigit(): __UpperCamelCase =model[int(SCREAMING_SNAKE_CASE__ )] __UpperCamelCase =old_model[int(SCREAMING_SNAKE_CASE__ )] else: __UpperCamelCase =getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if old_attribute == "": __UpperCamelCase =old_model else: if not hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError(F'{old_model} does not have {old_attribute}' ) __UpperCamelCase =getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not is_key_init: raise ValueError(F'{key} was not correctly initialized!' ) print(F'Saving model to {pytorch_dump_folder_path}' ) prophet.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_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.' ) _A = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =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] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =0 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) # No of vertices in graph __UpperCamelCase =[0] * n __UpperCamelCase =[False] * n def dfs(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =True __UpperCamelCase =id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , id_ ) __UpperCamelCase =min(low[at] , low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge __UpperCamelCase =min(low[at] , low[to] ) __UpperCamelCase =[] for i in range(SCREAMING_SNAKE_CASE__ ): if not visited[i]: dfs(SCREAMING_SNAKE_CASE__ , -1 , SCREAMING_SNAKE_CASE__ , id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str=[] ): __UpperCamelCase =size[0] - overlap_pixels * 2 __UpperCamelCase =size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels __UpperCamelCase =np.ones((size_y, size_x) , dtype=np.uinta ) * 2_55 __UpperCamelCase =np.pad(SCREAMING_SNAKE_CASE__ , mode='linear_ramp' , pad_width=SCREAMING_SNAKE_CASE__ , end_values=0 ) if "l" in remove_borders: __UpperCamelCase =mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: __UpperCamelCase =mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: __UpperCamelCase =mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: __UpperCamelCase =mask[0 : mask.shape[0] - overlap_pixels, :] return mask def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] ): return max(SCREAMING_SNAKE_CASE__ , min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : [int] , SCREAMING_SNAKE_CASE__ : [int] , SCREAMING_SNAKE_CASE__ : [int] ): return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : [int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : [int] ): __UpperCamelCase =list(SCREAMING_SNAKE_CASE__ ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap __UpperCamelCase =clamp_rect(SCREAMING_SNAKE_CASE__ , [0, 0] , [image_size[0], image_size[1]] ) return rect def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ): __UpperCamelCase =Image.new('RGB' , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(SCREAMING_SNAKE_CASE__ , (original_slice, 0) ) return result def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =(original_image_slice * 4, 0, tile.size[0], tile.size[1]) __UpperCamelCase =tile.crop(SCREAMING_SNAKE_CASE__ ) return tile def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __UpperCamelCase =n % d return n - divisor class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ = 350 , ) -> Union[str, Any]: super().__init__( vae=A_ , text_encoder=A_ , tokenizer=A_ , unet=A_ , low_res_scheduler=A_ , scheduler=A_ , max_noise_level=A_ , ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , **A_ ) -> Union[str, Any]: torch.manual_seed(0 ) __UpperCamelCase =( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) __UpperCamelCase =add_overlap_rect(A_ , A_ , image.size ) __UpperCamelCase =image.crop(A_ ) __UpperCamelCase =((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] __UpperCamelCase =translated_slice_x - (original_image_slice / 2) __UpperCamelCase =max(0 , A_ ) __UpperCamelCase =squeeze_tile(A_ , A_ , A_ , A_ ) __UpperCamelCase =to_input.size __UpperCamelCase =to_input.resize((tile_size, tile_size) , Image.BICUBIC ) __UpperCamelCase =super(A_ , self ).__call__(image=A_ , **A_ ).images[0] __UpperCamelCase =upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) __UpperCamelCase =unsqueeze_tile(A_ , A_ ) __UpperCamelCase =upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) __UpperCamelCase =[] if x == 0: remove_borders.append('l' ) elif crop_rect[2] == image.size[0]: remove_borders.append('r' ) if y == 0: remove_borders.append('t' ) elif crop_rect[3] == image.size[1]: remove_borders.append('b' ) __UpperCamelCase =Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=A_ ) , mode='L' , ) final_image.paste( A_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , A_ ) @torch.no_grad() def __call__( self , A_ , A_ , A_ = 75 , A_ = 9.0 , A_ = 50 , A_ = None , A_ = 1 , A_ = 0.0 , A_ = None , A_ = None , A_ = None , A_ = 1 , A_ = 128 , A_ = 32 , A_ = 32 , ) -> Tuple: __UpperCamelCase =Image.new('RGB' , (image.size[0] * 4, image.size[1] * 4) ) __UpperCamelCase =math.ceil(image.size[0] / tile_size ) __UpperCamelCase =math.ceil(image.size[1] / tile_size ) __UpperCamelCase =tcx * tcy __UpperCamelCase =0 for y in range(A_ ): for x in range(A_ ): self._process_tile( A_ , A_ , A_ , A_ , A_ , A_ , A_ , prompt=A_ , num_inference_steps=A_ , guidance_scale=A_ , noise_level=A_ , negative_prompt=A_ , num_images_per_prompt=A_ , eta=A_ , generator=A_ , latents=A_ , ) current_count += 1 if callback is not None: callback({'progress': current_count / total_tile_count, 'image': final_image} ) return final_image def _UpperCAmelCase ( ): # Run a demo __UpperCamelCase ='stabilityai/stable-diffusion-x4-upscaler' __UpperCamelCase =StableDiffusionTiledUpscalePipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , revision='fp16' , torch_dtype=torch.floataa ) __UpperCamelCase =pipe.to('cuda' ) __UpperCamelCase =Image.open('../../docs/source/imgs/diffusers_library.jpg' ) def callback(SCREAMING_SNAKE_CASE__ : List[str] ): print(F'progress: {obj["progress"]:.4f}' ) obj["image"].save('diffusers_library_progress.jpg' ) __UpperCamelCase =pipe(image=SCREAMING_SNAKE_CASE__ , prompt='Black font, white background, vector' , noise_level=40 , callback=SCREAMING_SNAKE_CASE__ ) final_image.save('diffusers_library.jpg' ) if __name__ == "__main__": main()
62
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
1
import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ): # Initialise PyTorch model __UpperCamelCase =AlbertConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(F'Building PyTorch model from configuration: {config}' ) __UpperCamelCase =AlbertForPreTraining(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tf_weights_in_albert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--albert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained ALBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _A = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers _A = '3' print('Python version:', sys.version) print('transformers version:', transformers.__version__) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) print('Cuda version:', torch.version.cuda) print('CuDNN version:', torch.backends.cudnn.version()) print('Number of GPUs available:', torch.cuda.device_count()) print('NCCL version:', torch.cuda.nccl.version()) except ImportError: print('Torch version:', None) try: import deepspeed print('DeepSpeed version:', deepspeed.__version__) except ImportError: print('DeepSpeed version:', None) try: import tensorflow as tf print('TensorFlow version:', tf.__version__) print('TF GPUs available:', bool(tf.config.list_physical_devices('GPU'))) print('Number of TF GPUs available:', len(tf.config.list_physical_devices('GPU'))) except ImportError: print('TensorFlow version:', None)
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
# 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] ): """simple docstring""" def __init__( self , A_=None , **A_ ) -> Union[str, Any]: super().__init__(features=A_ ) __UpperCamelCase =torch_tensor_kwargs import torch # noqa import torch at initialization def _a ( self , A_ ) -> Union[str, Any]: import torch if isinstance(A_ , A_ ) and column: if all( isinstance(A_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(A_ ) return column def _a ( self , A_ ) -> Any: import torch if isinstance(A_ , (str, bytes, type(A_ )) ): return value elif isinstance(A_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() __UpperCamelCase ={} if isinstance(A_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): __UpperCamelCase ={'dtype': torch.intaa} elif isinstance(A_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): __UpperCamelCase ={'dtype': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(A_ , PIL.Image.Image ): __UpperCamelCase =np.asarray(A_ ) return torch.tensor(A_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def _a ( self , A_ ) -> Any: import torch # support for torch, tf, jax etc. if hasattr(A_ , '__array__' ) and not isinstance(A_ , torch.Tensor ): __UpperCamelCase =data_struct.__array__() # support for nested types like struct of list of struct if isinstance(A_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(A_ ) for substruct in data_struct] ) elif isinstance(A_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(A_ ) for substruct in data_struct] ) return self._tensorize(A_ ) def _a ( self , A_ ) -> List[Any]: return map_nested(self._recursive_tensorize , A_ , map_list=A_ ) def _a ( self , A_ ) -> Mapping: __UpperCamelCase =self.numpy_arrow_extractor().extract_row(A_ ) __UpperCamelCase =self.python_features_decoder.decode_row(A_ ) return self.recursive_tensorize(A_ ) def _a ( self , A_ ) -> "torch.Tensor": __UpperCamelCase =self.numpy_arrow_extractor().extract_column(A_ ) __UpperCamelCase =self.python_features_decoder.decode_column(A_ , pa_table.column_names[0] ) __UpperCamelCase =self.recursive_tensorize(A_ ) __UpperCamelCase =self._consolidate(A_ ) return column def _a ( self , A_ ) -> Mapping: __UpperCamelCase =self.numpy_arrow_extractor().extract_batch(A_ ) __UpperCamelCase =self.python_features_decoder.decode_batch(A_ ) __UpperCamelCase =self.recursive_tensorize(A_ ) for column_name in batch: __UpperCamelCase =self._consolidate(batch[column_name] ) return batch
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
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 ConditionalDetrImageProcessor class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , A_ , A_=7 , A_=3 , A_=30 , A_=400 , A_=True , A_=None , A_=True , A_=[0.5, 0.5, 0.5] , A_=[0.5, 0.5, 0.5] , A_=True , A_=1 / 255 , A_=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __UpperCamelCase =size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =num_channels __UpperCamelCase =min_resolution __UpperCamelCase =max_resolution __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =do_normalize __UpperCamelCase =image_mean __UpperCamelCase =image_std __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_pad def _a ( self ) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _a ( self , A_ , A_=False ) -> Optional[int]: if not batched: __UpperCamelCase =image_inputs[0] if isinstance(A_ , Image.Image ): __UpperCamelCase , __UpperCamelCase =image.size else: __UpperCamelCase , __UpperCamelCase =image.shape[1], image.shape[2] if w < h: __UpperCamelCase =int(self.size['shortest_edge'] * h / w ) __UpperCamelCase =self.size['shortest_edge'] elif w > h: __UpperCamelCase =self.size['shortest_edge'] __UpperCamelCase =int(self.size['shortest_edge'] * w / h ) else: __UpperCamelCase =self.size['shortest_edge'] __UpperCamelCase =self.size['shortest_edge'] else: __UpperCamelCase =[] for image in image_inputs: __UpperCamelCase , __UpperCamelCase =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __UpperCamelCase =max(A_ , key=lambda A_ : item[0] )[0] __UpperCamelCase =max(A_ , key=lambda A_ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = ConditionalDetrImageProcessor if is_vision_available() else None def _a ( self ) -> Optional[Any]: __UpperCamelCase =ConditionalDetrImageProcessingTester(self ) @property def _a ( self ) -> Any: return self.image_processor_tester.prepare_image_processor_dict() def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ , 'image_mean' ) ) self.assertTrue(hasattr(A_ , 'image_std' ) ) self.assertTrue(hasattr(A_ , 'do_normalize' ) ) self.assertTrue(hasattr(A_ , 'do_resize' ) ) self.assertTrue(hasattr(A_ , 'size' ) ) def _a ( self ) -> List[str]: __UpperCamelCase =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , A_ ) __UpperCamelCase =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A_ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , A_ ) def _a ( self ) -> Dict: pass def _a ( self ) -> List[Any]: # Initialize image_processing __UpperCamelCase =self.image_processing_class(**self.image_processor_dict ) # create random PIL images __UpperCamelCase =prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ ) for image in image_inputs: self.assertIsInstance(A_ , Image.Image ) # Test not batched input __UpperCamelCase =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ , batched=A_ ) __UpperCamelCase =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, expected_height, expected_width, ) , ) def _a ( self ) -> Any: # Initialize image_processing __UpperCamelCase =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __UpperCamelCase =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 __UpperCamelCase =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase =image_processing(A_ , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ , batched=A_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ) -> Tuple: # Initialize image_processing __UpperCamelCase =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __UpperCamelCase =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 __UpperCamelCase =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase =image_processing(A_ , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ , batched=A_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _a ( self ) -> Union[str, Any]: # prepare image and target __UpperCamelCase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __UpperCamelCase =json.loads(f.read() ) __UpperCamelCase ={'image_id': 39769, 'annotations': target} # encode them __UpperCamelCase =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) __UpperCamelCase =image_processing(images=A_ , annotations=A_ , return_tensors='pt' ) # verify pixel values __UpperCamelCase =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , A_ ) __UpperCamelCase =torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , A_ , atol=1E-4 ) ) # verify area __UpperCamelCase =torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , A_ ) ) # verify boxes __UpperCamelCase =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , A_ ) __UpperCamelCase =torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , A_ , atol=1E-3 ) ) # verify image_id __UpperCamelCase =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , A_ ) ) # verify is_crowd __UpperCamelCase =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , A_ ) ) # verify class_labels __UpperCamelCase =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , A_ ) ) # verify orig_size __UpperCamelCase =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , A_ ) ) # verify size __UpperCamelCase =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , A_ ) ) @slow def _a ( self ) -> Dict: # prepare image, target and masks_path __UpperCamelCase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __UpperCamelCase =json.loads(f.read() ) __UpperCamelCase ={'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __UpperCamelCase =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __UpperCamelCase =ConditionalDetrImageProcessor(format='coco_panoptic' ) __UpperCamelCase =image_processing(images=A_ , annotations=A_ , masks_path=A_ , return_tensors='pt' ) # verify pixel values __UpperCamelCase =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , A_ ) __UpperCamelCase =torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , A_ , atol=1E-4 ) ) # verify area __UpperCamelCase =torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , A_ ) ) # verify boxes __UpperCamelCase =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , A_ ) __UpperCamelCase =torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , A_ , atol=1E-3 ) ) # verify image_id __UpperCamelCase =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , A_ ) ) # verify is_crowd __UpperCamelCase =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , A_ ) ) # verify class_labels __UpperCamelCase =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , A_ ) ) # verify masks __UpperCamelCase =822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , A_ ) # verify orig_size __UpperCamelCase =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , A_ ) ) # verify size __UpperCamelCase =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , A_ ) )
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =20 * np.logaa(SCREAMING_SNAKE_CASE__ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds __UpperCamelCase =get_bounds(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE__ , -2 * pi ) ) plt.show()
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _A = {'configuration_swin': ['SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwinConfig', 'SwinOnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SWIN_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwinForImageClassification', 'SwinForMaskedImageModeling', 'SwinModel', 'SwinPreTrainedModel', 'SwinBackbone', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSwinForImageClassification', 'TFSwinForMaskedImageModeling', 'TFSwinModel', 'TFSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Dict = "deta" UpperCAmelCase__ : str = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , A_=None , A_=900 , A_=2048 , A_=6 , A_=2048 , A_=8 , A_=6 , A_=1024 , A_=8 , A_=0.0 , A_=True , A_="relu" , A_=256 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=1.0 , A_=True , A_=False , A_="sine" , A_=5 , A_=4 , A_=4 , A_=True , A_=300 , A_=True , A_=True , A_=1 , A_=5 , A_=2 , A_=1 , A_=1 , A_=5 , A_=2 , A_=0.1 , A_=0.25 , **A_ , ) -> Optional[int]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __UpperCamelCase =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(A_ , A_ ): __UpperCamelCase =backbone_config.pop('model_type' ) __UpperCamelCase =CONFIG_MAPPING[backbone_model_type] __UpperCamelCase =config_class.from_dict(A_ ) __UpperCamelCase =backbone_config __UpperCamelCase =num_queries __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =init_xavier_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =auxiliary_loss __UpperCamelCase =position_embedding_type # deformable attributes __UpperCamelCase =num_feature_levels __UpperCamelCase =encoder_n_points __UpperCamelCase =decoder_n_points __UpperCamelCase =two_stage __UpperCamelCase =two_stage_num_proposals __UpperCamelCase =with_box_refine __UpperCamelCase =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =mask_loss_coefficient __UpperCamelCase =dice_loss_coefficient __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient __UpperCamelCase =focal_alpha super().__init__(is_encoder_decoder=A_ , **A_ ) @property def _a ( self ) -> int: return self.encoder_attention_heads @property def _a ( self ) -> int: return self.d_model def _a ( self ) -> Any: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.backbone_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( 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_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =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.' )
62
1
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = PriorTransformer UpperCAmelCase__ : List[str] = "hidden_states" @property def _a ( self ) -> int: __UpperCamelCase =4 __UpperCamelCase =8 __UpperCamelCase =7 __UpperCamelCase =floats_tensor((batch_size, embedding_dim) ).to(A_ ) __UpperCamelCase =floats_tensor((batch_size, embedding_dim) ).to(A_ ) __UpperCamelCase =floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(A_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def _a ( self , A_=0 ) -> Dict: torch.manual_seed(A_ ) __UpperCamelCase =4 __UpperCamelCase =8 __UpperCamelCase =7 __UpperCamelCase =torch.randn((batch_size, embedding_dim) ).to(A_ ) __UpperCamelCase =torch.randn((batch_size, embedding_dim) ).to(A_ ) __UpperCamelCase =torch.randn((batch_size, num_embeddings, embedding_dim) ).to(A_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def _a ( self ) -> Tuple: return (4, 8) @property def _a ( self ) -> List[Any]: return (4, 8) def _a ( self ) -> str: __UpperCamelCase ={ 'num_attention_heads': 2, 'attention_head_dim': 4, 'num_layers': 2, 'embedding_dim': 8, 'num_embeddings': 7, 'additional_embeddings': 4, } __UpperCamelCase =self.dummy_input return init_dict, inputs_dict def _a ( self ) -> Union[str, Any]: __UpperCamelCase , __UpperCamelCase =PriorTransformer.from_pretrained( 'hf-internal-testing/prior-dummy' , output_loading_info=A_ ) self.assertIsNotNone(A_ ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(A_ ) __UpperCamelCase =model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def _a ( self ) -> Any: __UpperCamelCase , __UpperCamelCase =self.prepare_init_args_and_inputs_for_common() __UpperCamelCase =self.model_class(**A_ ) __UpperCamelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase =[*signature.parameters.keys()] __UpperCamelCase =['hidden_states', 'timestep'] self.assertListEqual(arg_names[:2] , A_ ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =PriorTransformer.from_pretrained('hf-internal-testing/prior-dummy' ) __UpperCamelCase =model.to(A_ ) if hasattr(A_ , 'set_default_attn_processor' ): model.set_default_attn_processor() __UpperCamelCase =self.get_dummy_seed_input() with torch.no_grad(): __UpperCamelCase =model(**A_ )[0] __UpperCamelCase =output[0, :5].flatten().cpu() print(A_ ) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. __UpperCamelCase =torch.tensor([-1.3436, -0.2870, 0.7538, 0.4368, -0.0239] ) self.assertTrue(torch_all_close(A_ , A_ , rtol=1E-2 ) ) @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self , A_=1 , A_=768 , A_=77 , A_=0 ) -> Union[str, Any]: torch.manual_seed(A_ ) __UpperCamelCase =batch_size __UpperCamelCase =embedding_dim __UpperCamelCase =num_embeddings __UpperCamelCase =torch.randn((batch_size, embedding_dim) ).to(A_ ) __UpperCamelCase =torch.randn((batch_size, embedding_dim) ).to(A_ ) __UpperCamelCase =torch.randn((batch_size, num_embeddings, embedding_dim) ).to(A_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def _a ( self ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.5861, 0.1283, -0.0931, 0.0882, 0.4476, 0.1329, -0.0498, 0.0640]], [37, [-0.4913, 0.0110, -0.0483, 0.0541, 0.4954, -0.0170, 0.0354, 0.1651]], # fmt: on ] ) def _a ( self , A_ , A_ ) -> int: __UpperCamelCase =PriorTransformer.from_pretrained('kandinsky-community/kandinsky-2-1-prior' , subfolder='prior' ) model.to(A_ ) __UpperCamelCase =self.get_dummy_seed_input(seed=A_ ) with torch.no_grad(): __UpperCamelCase =model(**A_ )[0] assert list(sample.shape ) == [1, 768] __UpperCamelCase =sample[0, :8].flatten().cpu() print(A_ ) __UpperCamelCase =torch.tensor(A_ ) assert torch_all_close(A_ , A_ , atol=1E-3 )
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=False , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ) -> int: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =seq_length __UpperCamelCase =is_training __UpperCamelCase =use_input_mask __UpperCamelCase =use_token_type_ids __UpperCamelCase =use_labels __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =type_vocab_size __UpperCamelCase =type_sequence_label_size __UpperCamelCase =initializer_range __UpperCamelCase =num_labels __UpperCamelCase =num_choices __UpperCamelCase =scope def _a ( self ) -> Dict: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase =None if self.use_input_mask: __UpperCamelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase =None if self.use_token_type_ids: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase =ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> int: return OpenLlamaConfig( 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=A_ , initializer_range=self.initializer_range , use_stable_embedding=A_ , ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Dict: __UpperCamelCase =OpenLlamaModel(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ ) __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> Optional[int]: __UpperCamelCase =True __UpperCamelCase =OpenLlamaModel(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , ) __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , ) __UpperCamelCase =model(A_ , attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> Union[str, Any]: __UpperCamelCase =OpenLlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> List[Any]: __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =OpenLlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() # first forward pass __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , use_cache=A_ , ) __UpperCamelCase =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __UpperCamelCase =ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __UpperCamelCase =torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCamelCase =torch.cat([input_mask, next_mask] , dim=-1 ) __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , output_hidden_states=A_ , )['hidden_states'][0] __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , past_key_values=A_ , output_hidden_states=A_ , )['hidden_states'][0] # select random slice __UpperCamelCase =ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCamelCase =output_from_no_past[:, -3:, random_slice_idx].detach() __UpperCamelCase =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A_ , A_ , atol=1E-3 ) ) def _a ( self ) -> List[str]: __UpperCamelCase =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) =config_and_inputs __UpperCamelCase ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase__ ( A_ , A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) UpperCAmelCase__ : List[Any] = (OpenLlamaForCausalLM,) if is_torch_available() else () UpperCAmelCase__ : str = ( { "feature-extraction": OpenLlamaModel, "text-classification": OpenLlamaForSequenceClassification, "text-generation": OpenLlamaForCausalLM, "zero-shot": OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Optional[int] = False def _a ( self ) -> List[str]: __UpperCamelCase =OpenLlamaModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , hidden_size=37 ) def _a ( self ) -> Tuple: self.config_tester.run_common_tests() def _a ( self ) -> Any: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> str: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCamelCase =type self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> Dict: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCamelCase =OpenLlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase ='single_label_classification' __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCamelCase =OpenLlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase ='multi_label_classification' __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __UpperCamelCase =OpenLlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test' ) def _a ( self ) -> List[Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =ids_tensor([1, 10] , config.vocab_size ) __UpperCamelCase =ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCamelCase =OpenLlamaModel(A_ ) original_model.to(A_ ) original_model.eval() __UpperCamelCase =original_model(A_ ).last_hidden_state __UpperCamelCase =original_model(A_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCamelCase ={'type': scaling_type, 'factor': 10.0} __UpperCamelCase =OpenLlamaModel(A_ ) scaled_model.to(A_ ) scaled_model.eval() __UpperCamelCase =scaled_model(A_ ).last_hidden_state __UpperCamelCase =scaled_model(A_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(A_ , A_ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(A_ , A_ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(A_ , A_ , atol=1E-5 ) )
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
import os import time import numpy as np import onnxruntime as ort _A = '1' _A = '0' _A = '1' _A = ort.SessionOptions() _A = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('Create inference session...') _A = ['TensorrtExecutionProvider', 'CUDAExecutionProvider'] _A = ort.InferenceSession('model.onnx', sess_options=sess_opt, providers=execution_provider) _A = ort.RunOptions() _A = 128 _A = 1 _A = np.ones((batch, sequence), dtype=np.intaa) _A = np.ones((batch, sequence), dtype=np.intaa) _A = np.ones((batch, sequence), dtype=np.intaa) print('Warm up phase...') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('Start inference...') _A = time.time() _A = 2000 _A = {} for iter in range(max_iters): _A = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('Average Inference Time = {:.3f} ms'.format((time.time() - start_time) * 1000 / max_iters))
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = {'configuration_glpn': ['GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GLPNConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['GLPNFeatureExtractor'] _A = ['GLPNImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'GLPN_PRETRAINED_MODEL_ARCHIVE_LIST', 'GLPNForDepthEstimation', 'GLPNLayer', 'GLPNModel', 'GLPNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[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] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
import string def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): for key in range(len(string.ascii_uppercase ) ): __UpperCamelCase ='' for symbol in message: if symbol in string.ascii_uppercase: __UpperCamelCase =string.ascii_uppercase.find(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =num - key if num < 0: __UpperCamelCase =num + len(string.ascii_uppercase ) __UpperCamelCase =translated + string.ascii_uppercase[num] else: __UpperCamelCase =translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def _UpperCAmelCase ( ): __UpperCamelCase =input('Encrypted message: ' ) __UpperCamelCase =message.upper() decrypt(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( 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_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =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.' )
62
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ) -> PIL.Image.Image: __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(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =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.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
import os def _UpperCAmelCase ( ): with open(os.path.dirname(SCREAMING_SNAKE_CASE__ ) + '/p022_names.txt' ) as file: __UpperCamelCase =str(file.readlines()[0] ) __UpperCamelCase =names.replace('"' , '' ).split(',' ) names.sort() __UpperCamelCase =0 __UpperCamelCase =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 __UpperCamelCase =0 return total_score if __name__ == "__main__": print(solution())
62
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 _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =generate_pascal_triangle(SCREAMING_SNAKE_CASE__ ) for row_idx in range(SCREAMING_SNAKE_CASE__ ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=' ' ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=' ' ) else: print(triangle[row_idx][col_idx] , end='' ) print() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('The input value of \'num_rows\' should be \'int\'' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( 'The input value of \'num_rows\' should be greater than or equal to 0' ) __UpperCamelCase =[] for current_row_idx in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =populate_current_row(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) triangle.append(SCREAMING_SNAKE_CASE__ ) return triangle def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 __UpperCamelCase , __UpperCamelCase =1, 1 for current_col_idx in range(1 , SCREAMING_SNAKE_CASE__ ): calculate_current_element( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return current_row def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , ): __UpperCamelCase =triangle[current_row_idx - 1][current_col_idx - 1] __UpperCamelCase =triangle[current_row_idx - 1][current_col_idx] __UpperCamelCase =above_to_left_elt + above_to_right_elt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('The input value of \'num_rows\' should be \'int\'' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( 'The input value of \'num_rows\' should be greater than or equal to 0' ) __UpperCamelCase =[[1]] for row_index in range(1 , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[0] + result[-1] + [0] __UpperCamelCase =row_index + 1 # Calculate the number of distinct elements in a row __UpperCamelCase =sum(divmod(SCREAMING_SNAKE_CASE__ , 2 ) ) __UpperCamelCase =[ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] __UpperCamelCase =row_first_half[: (row_index + 1) // 2] row_second_half.reverse() __UpperCamelCase =row_first_half + row_second_half result.append(SCREAMING_SNAKE_CASE__ ) return result def _UpperCAmelCase ( ): from collections.abc import Callable from timeit import timeit def benchmark_a_function(SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : int ) -> None: __UpperCamelCase =F'{func.__name__}({value})' __UpperCamelCase =timeit(F'__main__.{call}' , setup='import __main__' ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(F'{call:38} -- {timing:.4f} seconds' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from dataclasses import dataclass from typing import Dict, 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 .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : "DiagonalGaussianDistribution" class UpperCAmelCase__ ( A_ , A_ ): """simple docstring""" UpperCAmelCase__ : List[Any] = True @register_to_config def __init__( self , A_ = 3 , A_ = 3 , A_ = ("DownEncoderBlock2D",) , A_ = ("UpDecoderBlock2D",) , A_ = (64,) , A_ = 1 , A_ = "silu" , A_ = 4 , A_ = 32 , A_ = 32 , A_ = 0.1_8215 , ) -> Any: super().__init__() # pass init params to Encoder __UpperCamelCase =Encoder( in_channels=A_ , out_channels=A_ , down_block_types=A_ , block_out_channels=A_ , layers_per_block=A_ , act_fn=A_ , norm_num_groups=A_ , double_z=A_ , ) # pass init params to Decoder __UpperCamelCase =Decoder( in_channels=A_ , out_channels=A_ , up_block_types=A_ , block_out_channels=A_ , layers_per_block=A_ , norm_num_groups=A_ , act_fn=A_ , ) __UpperCamelCase =nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) __UpperCamelCase =nn.Convad(A_ , A_ , 1 ) __UpperCamelCase =False __UpperCamelCase =False # only relevant if vae tiling is enabled __UpperCamelCase =self.config.sample_size __UpperCamelCase =( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) __UpperCamelCase =int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) __UpperCamelCase =0.25 def _a ( self , A_ , A_=False ) -> Any: if isinstance(A_ , (Encoder, Decoder) ): __UpperCamelCase =value def _a ( self , A_ = True ) -> List[Any]: __UpperCamelCase =use_tiling def _a ( self ) -> Union[str, Any]: self.enable_tiling(A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =True def _a ( self ) -> Any: __UpperCamelCase =False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def _a ( self ) -> Dict[str, AttentionProcessor]: __UpperCamelCase ={} def fn_recursive_add_processors(A_ , A_ , A_ ): if hasattr(A_ , 'set_processor' ): __UpperCamelCase =module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'{name}.{sub_name}' , A_ , A_ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(A_ , A_ , A_ ) return processors def _a ( self , A_ ) -> Tuple: __UpperCamelCase =len(self.attn_processors.keys() ) if isinstance(A_ , A_ ) and len(A_ ) != count: raise ValueError( f'A dict of processors was passed, but the number of processors {len(A_ )} does not match the' f' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(A_ , A_ , A_ ): if hasattr(A_ , 'set_processor' ): if not isinstance(A_ , A_ ): module.set_processor(A_ ) else: module.set_processor(processor.pop(f'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'{name}.{sub_name}' , A_ , A_ ) for name, module in self.named_children(): fn_recursive_attn_processor(A_ , A_ , A_ ) def _a ( self ) -> List[Any]: self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def _a ( self , A_ , A_ = True ) -> AutoencoderKLOutput: if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(A_ , return_dict=A_ ) if self.use_slicing and x.shape[0] > 1: __UpperCamelCase =[self.encoder(A_ ) for x_slice in x.split(1 )] __UpperCamelCase =torch.cat(A_ ) else: __UpperCamelCase =self.encoder(A_ ) __UpperCamelCase =self.quant_conv(A_ ) __UpperCamelCase =DiagonalGaussianDistribution(A_ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=A_ ) def _a ( self , A_ , A_ = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(A_ , return_dict=A_ ) __UpperCamelCase =self.post_quant_conv(A_ ) __UpperCamelCase =self.decoder(A_ ) if not return_dict: return (dec,) return DecoderOutput(sample=A_ ) @apply_forward_hook def _a ( self , A_ , A_ = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_slicing and z.shape[0] > 1: __UpperCamelCase =[self._decode(A_ ).sample for z_slice in z.split(1 )] __UpperCamelCase =torch.cat(A_ ) else: __UpperCamelCase =self._decode(A_ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=A_ ) def _a ( self , A_ , A_ , A_ ) -> Optional[Any]: __UpperCamelCase =min(a.shape[2] , b.shape[2] , A_ ) for y in range(A_ ): __UpperCamelCase =a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def _a ( self , A_ , A_ , A_ ) -> Dict: __UpperCamelCase =min(a.shape[3] , b.shape[3] , A_ ) for x in range(A_ ): __UpperCamelCase =a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def _a ( self , A_ , A_ = True ) -> AutoencoderKLOutput: __UpperCamelCase =int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) __UpperCamelCase =int(self.tile_latent_min_size * self.tile_overlap_factor ) __UpperCamelCase =self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. __UpperCamelCase =[] for i in range(0 , x.shape[2] , A_ ): __UpperCamelCase =[] for j in range(0 , x.shape[3] , A_ ): __UpperCamelCase =x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] __UpperCamelCase =self.encoder(A_ ) __UpperCamelCase =self.quant_conv(A_ ) row.append(A_ ) rows.append(A_ ) __UpperCamelCase =[] for i, row in enumerate(A_ ): __UpperCamelCase =[] for j, tile in enumerate(A_ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: __UpperCamelCase =self.blend_v(rows[i - 1][j] , A_ , A_ ) if j > 0: __UpperCamelCase =self.blend_h(row[j - 1] , A_ , A_ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(A_ , dim=3 ) ) __UpperCamelCase =torch.cat(A_ , dim=2 ) __UpperCamelCase =DiagonalGaussianDistribution(A_ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=A_ ) def _a ( self , A_ , A_ = True ) -> Union[DecoderOutput, torch.FloatTensor]: __UpperCamelCase =int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) __UpperCamelCase =int(self.tile_sample_min_size * self.tile_overlap_factor ) __UpperCamelCase =self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. __UpperCamelCase =[] for i in range(0 , z.shape[2] , A_ ): __UpperCamelCase =[] for j in range(0 , z.shape[3] , A_ ): __UpperCamelCase =z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] __UpperCamelCase =self.post_quant_conv(A_ ) __UpperCamelCase =self.decoder(A_ ) row.append(A_ ) rows.append(A_ ) __UpperCamelCase =[] for i, row in enumerate(A_ ): __UpperCamelCase =[] for j, tile in enumerate(A_ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: __UpperCamelCase =self.blend_v(rows[i - 1][j] , A_ , A_ ) if j > 0: __UpperCamelCase =self.blend_h(row[j - 1] , A_ , A_ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(A_ , dim=3 ) ) __UpperCamelCase =torch.cat(A_ , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=A_ ) def _a ( self , A_ , A_ = False , A_ = True , A_ = None , ) -> Union[DecoderOutput, torch.FloatTensor]: __UpperCamelCase =sample __UpperCamelCase =self.encode(A_ ).latent_dist if sample_posterior: __UpperCamelCase =posterior.sample(generator=A_ ) else: __UpperCamelCase =posterior.mode() __UpperCamelCase =self.decode(A_ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=A_ )
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : int ): if digit_amount > 0: return round(number - int(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) return number - int(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
import functools from typing import Any def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ): # Validation if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or len(SCREAMING_SNAKE_CASE__ ) == 0: raise ValueError('the string should be not empty string' ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not all( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) > 0 for item in words ): raise ValueError('the words should be a list of non-empty strings' ) # Build trie __UpperCamelCase ={} __UpperCamelCase ='WORD_KEEPER' for word in words: __UpperCamelCase =trie for c in word: if c not in trie_node: __UpperCamelCase ={} __UpperCamelCase =trie_node[c] __UpperCamelCase =True __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) # Dynamic programming method @functools.cache def is_breakable(SCREAMING_SNAKE_CASE__ : int ) -> bool: if index == len_string: return True __UpperCamelCase =trie for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =trie_node.get(string[i] , SCREAMING_SNAKE_CASE__ ) if trie_node is None: return False if trie_node.get(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _A = { 'configuration_owlvit': [ 'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OwlViTConfig', 'OwlViTOnnxConfig', 'OwlViTTextConfig', 'OwlViTVisionConfig', ], 'processing_owlvit': ['OwlViTProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['OwlViTFeatureExtractor'] _A = ['OwlViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OwlViTModel', 'OwlViTPreTrainedModel', 'OwlViTTextModel', 'OwlViTVisionModel', 'OwlViTForObjectDetection', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm _A = re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex _A = 10 _A = 256 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] ): if len(SCREAMING_SNAKE_CASE__ ) < MIN_NUM_TOKENS: return None __UpperCamelCase =MinHash(num_perm=SCREAMING_SNAKE_CASE__ ) for token in set(SCREAMING_SNAKE_CASE__ ): min_hash.update(token.encode() ) return min_hash def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): return {t for t in NON_ALPHA.split(SCREAMING_SNAKE_CASE__ ) if len(t.strip() ) > 0} class UpperCAmelCase__ : """simple docstring""" def __init__( self , *, A_ = 0.85 , ) -> str: __UpperCamelCase =duplication_jaccard_threshold __UpperCamelCase =NUM_PERM __UpperCamelCase =MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __UpperCamelCase =defaultdict(A_ ) def _a ( self , A_ , A_ ) -> None: __UpperCamelCase =self._index.query(A_ ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(A_ , A_ ) if len(A_ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(A_ ) break else: self._duplicate_clusters[close_duplicates[0]].add(A_ ) def _a ( self ) -> List[List[Dict]]: __UpperCamelCase =[] for base, duplicates in self._duplicate_clusters.items(): __UpperCamelCase =[base] + list(A_ ) # reformat the cluster to be a list of dict __UpperCamelCase =[{'base_index': el[0], 'repo_name': el[1], 'path': el[2]} for el in cluster] duplicate_clusters.append(A_ ) return duplicate_clusters def _a ( self , A_ ) -> None: __UpperCamelCase =self.get_duplicate_clusters() with open(A_ , 'w' ) as f: json.dump(A_ , A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] ): __UpperCamelCase , __UpperCamelCase =element __UpperCamelCase =get_min_hash([t for t in NON_ALPHA.split(data['content'] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Type[Dataset] ): with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(SCREAMING_SNAKE_CASE__ , max_queue_size=1_00_00 ) , chunksize=1_00 , ): if data is not None: yield data def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Type[Dataset] , SCREAMING_SNAKE_CASE__ : float ): __UpperCamelCase =DuplicationIndex(duplication_jaccard_threshold=SCREAMING_SNAKE_CASE__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(SCREAMING_SNAKE_CASE__ ) ) , max_queue_size=1_00 ) ): di.add(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =get_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =get_tokens(SCREAMING_SNAKE_CASE__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) _A = None def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[] for elementa in cluster: __UpperCamelCase =_shared_dataset[elementa['base_index']]['content'] for elementa in extremes: __UpperCamelCase =_shared_dataset[elementa['base_index']]['content'] if jaccard_similarity(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __UpperCamelCase =1 extremes.append(SCREAMING_SNAKE_CASE__ ) return extremes def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ): global _shared_dataset __UpperCamelCase =dataset __UpperCamelCase =[] __UpperCamelCase =partial(_find_cluster_extremes_shared , jaccard_threshold=SCREAMING_SNAKE_CASE__ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) , total=len(SCREAMING_SNAKE_CASE__ ) , ): extremes_list.append(SCREAMING_SNAKE_CASE__ ) return extremes_list def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Type[Dataset] , SCREAMING_SNAKE_CASE__ : float = 0.85 ): __UpperCamelCase =make_duplicate_clusters(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase ={x['base_index'] for cluster in duplicate_clusters for x in cluster} __UpperCamelCase ={} __UpperCamelCase =find_extremes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for extremes in extremes_clusters: for element in extremes: __UpperCamelCase =element __UpperCamelCase =duplicate_indices - set(extreme_dict.keys() ) __UpperCamelCase =dataset.filter(lambda SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : idx not in remove_indices , with_indices=SCREAMING_SNAKE_CASE__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __UpperCamelCase =element['base_index'] in extreme_dict if element["is_extreme"]: __UpperCamelCase =extreme_dict[element['base_index']]['copies'] print(F'Original dataset size: {len(SCREAMING_SNAKE_CASE__ )}' ) print(F'Number of duplicate clusters: {len(SCREAMING_SNAKE_CASE__ )}' ) print(F'Files in duplicate cluster: {len(SCREAMING_SNAKE_CASE__ )}' ) print(F'Unique files in duplicate cluster: {len(SCREAMING_SNAKE_CASE__ )}' ) print(F'Filtered dataset size: {len(SCREAMING_SNAKE_CASE__ )}' ) return ds_filter, duplicate_clusters
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =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] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str = field( metadata={"help": "The output directory where the model will be written."} , ) UpperCAmelCase__ : str = field( metadata={ "help": ( "The encoder model checkpoint for weights initialization." "Don't set if you want to train an encoder model from scratch." ) } , ) UpperCAmelCase__ : str = field( metadata={ "help": ( "The decoder model checkpoint for weights initialization." "Don't set if you want to train a decoder model from scratch." ) } , ) UpperCAmelCase__ : Optional[str] = field( default=A_ , metadata={"help": "Pretrained encoder config name or path if not the same as encoder_model_name"} ) UpperCAmelCase__ : Optional[str] = field( default=A_ , metadata={"help": "Pretrained decoder config name or path if not the same as decoder_model_name"} ) def _UpperCAmelCase ( ): __UpperCamelCase =HfArgumentParser((ModelArguments,) ) ((__UpperCamelCase) , ) =parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: __UpperCamelCase =AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: __UpperCamelCase =AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: __UpperCamelCase =AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: __UpperCamelCase =AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=SCREAMING_SNAKE_CASE__ , decoder_config=SCREAMING_SNAKE_CASE__ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens __UpperCamelCase =decoder_config.decoder_start_token_id __UpperCamelCase =decoder_config.pad_token_id if decoder_start_token_id is None: __UpperCamelCase =decoder_config.bos_token_id if pad_token_id is None: __UpperCamelCase =decoder_config.eos_token_id # This is necessary to make Flax's generate() work __UpperCamelCase =decoder_config.eos_token_id __UpperCamelCase =decoder_start_token_id __UpperCamelCase =pad_token_id __UpperCamelCase =AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) __UpperCamelCase =AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10_00 ): return sum(e for e in range(3 , SCREAMING_SNAKE_CASE__ ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f"""{solution() = }""")
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
from math import factorial def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 1_00 ): return sum(map(SCREAMING_SNAKE_CASE__ , str(factorial(SCREAMING_SNAKE_CASE__ ) ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
62
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : List[str] = (DEISMultistepScheduler,) UpperCAmelCase__ : List[Any] = (("num_inference_steps", 2_5),) def _a ( self , **A_ ) -> Dict: __UpperCamelCase ={ 'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, } config.update(**A_ ) return config def _a ( self , A_=0 , **A_ ) -> Union[str, Any]: __UpperCamelCase =dict(self.forward_default_kwargs ) __UpperCamelCase =kwargs.pop('num_inference_steps' , A_ ) __UpperCamelCase =self.dummy_sample __UpperCamelCase =0.1 * sample __UpperCamelCase =[residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __UpperCamelCase =self.get_scheduler_config(**A_ ) __UpperCamelCase =scheduler_class(**A_ ) scheduler.set_timesteps(A_ ) # copy over dummy past residuals __UpperCamelCase =dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A_ ) __UpperCamelCase =scheduler_class.from_pretrained(A_ ) new_scheduler.set_timesteps(A_ ) # copy over dummy past residuals __UpperCamelCase =dummy_past_residuals[: new_scheduler.config.solver_order] __UpperCamelCase , __UpperCamelCase =sample, sample for t in range(A_ , time_step + scheduler.config.solver_order + 1 ): __UpperCamelCase =scheduler.step(A_ , A_ , A_ , **A_ ).prev_sample __UpperCamelCase =new_scheduler.step(A_ , A_ , A_ , **A_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _a ( self ) -> Dict: pass def _a ( self , A_=0 , **A_ ) -> List[str]: __UpperCamelCase =dict(self.forward_default_kwargs ) __UpperCamelCase =kwargs.pop('num_inference_steps' , A_ ) __UpperCamelCase =self.dummy_sample __UpperCamelCase =0.1 * sample __UpperCamelCase =[residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __UpperCamelCase =self.get_scheduler_config() __UpperCamelCase =scheduler_class(**A_ ) scheduler.set_timesteps(A_ ) # copy over dummy past residuals (must be after setting timesteps) __UpperCamelCase =dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A_ ) __UpperCamelCase =scheduler_class.from_pretrained(A_ ) # copy over dummy past residuals new_scheduler.set_timesteps(A_ ) # copy over dummy past residual (must be after setting timesteps) __UpperCamelCase =dummy_past_residuals[: new_scheduler.config.solver_order] __UpperCamelCase =scheduler.step(A_ , A_ , A_ , **A_ ).prev_sample __UpperCamelCase =new_scheduler.step(A_ , A_ , A_ , **A_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _a ( self , A_=None , **A_ ) -> Any: if scheduler is None: __UpperCamelCase =self.scheduler_classes[0] __UpperCamelCase =self.get_scheduler_config(**A_ ) __UpperCamelCase =scheduler_class(**A_ ) __UpperCamelCase =self.scheduler_classes[0] __UpperCamelCase =self.get_scheduler_config(**A_ ) __UpperCamelCase =scheduler_class(**A_ ) __UpperCamelCase =10 __UpperCamelCase =self.dummy_model() __UpperCamelCase =self.dummy_sample_deter scheduler.set_timesteps(A_ ) for i, t in enumerate(scheduler.timesteps ): __UpperCamelCase =model(A_ , A_ ) __UpperCamelCase =scheduler.step(A_ , A_ , A_ ).prev_sample return sample def _a ( self ) -> int: __UpperCamelCase =dict(self.forward_default_kwargs ) __UpperCamelCase =kwargs.pop('num_inference_steps' , A_ ) for scheduler_class in self.scheduler_classes: __UpperCamelCase =self.get_scheduler_config() __UpperCamelCase =scheduler_class(**A_ ) __UpperCamelCase =self.dummy_sample __UpperCamelCase =0.1 * sample if num_inference_steps is not None and hasattr(A_ , 'set_timesteps' ): scheduler.set_timesteps(A_ ) elif num_inference_steps is not None and not hasattr(A_ , '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.10] __UpperCamelCase =dummy_past_residuals[: scheduler.config.solver_order] __UpperCamelCase =scheduler.timesteps[5] __UpperCamelCase =scheduler.timesteps[6] __UpperCamelCase =scheduler.step(A_ , A_ , A_ , **A_ ).prev_sample __UpperCamelCase =scheduler.step(A_ , A_ , A_ , **A_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _a ( self ) -> List[Any]: # make sure that iterating over schedulers with same config names gives same results # for defaults __UpperCamelCase =DEISMultistepScheduler(**self.get_scheduler_config() ) __UpperCamelCase =self.full_loop(scheduler=A_ ) __UpperCamelCase =torch.mean(torch.abs(A_ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1E-3 __UpperCamelCase =DPMSolverSinglestepScheduler.from_config(scheduler.config ) __UpperCamelCase =DPMSolverMultistepScheduler.from_config(scheduler.config ) __UpperCamelCase =UniPCMultistepScheduler.from_config(scheduler.config ) __UpperCamelCase =DEISMultistepScheduler.from_config(scheduler.config ) __UpperCamelCase =self.full_loop(scheduler=A_ ) __UpperCamelCase =torch.mean(torch.abs(A_ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1E-3 def _a ( self ) -> Dict: for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=A_ ) def _a ( self ) -> Tuple: self.check_over_configs(thresholding=A_ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=A_ , prediction_type=A_ , sample_max_value=A_ , algorithm_type='deis' , solver_order=A_ , solver_type=A_ , ) def _a ( self ) -> Tuple: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A_ ) def _a ( self ) -> Any: for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=A_ , solver_type=A_ , prediction_type=A_ , algorithm_type=A_ , ) __UpperCamelCase =self.full_loop( solver_order=A_ , solver_type=A_ , prediction_type=A_ , algorithm_type=A_ , ) assert not torch.isnan(A_ ).any(), "Samples have nan numbers" def _a ( self ) -> int: self.check_over_configs(lower_order_final=A_ ) self.check_over_configs(lower_order_final=A_ ) def _a ( self ) -> int: for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=A_ , time_step=0 ) def _a ( self ) -> List[str]: __UpperCamelCase =self.full_loop() __UpperCamelCase =torch.mean(torch.abs(A_ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1E-3 def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.full_loop(prediction_type='v_prediction' ) __UpperCamelCase =torch.mean(torch.abs(A_ ) ) assert abs(result_mean.item() - 0.091 ) < 1E-3 def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.scheduler_classes[0] __UpperCamelCase =self.get_scheduler_config(thresholding=A_ , dynamic_thresholding_ratio=0 ) __UpperCamelCase =scheduler_class(**A_ ) __UpperCamelCase =10 __UpperCamelCase =self.dummy_model() __UpperCamelCase =self.dummy_sample_deter.half() scheduler.set_timesteps(A_ ) for i, t in enumerate(scheduler.timesteps ): __UpperCamelCase =model(A_ , A_ ) __UpperCamelCase =scheduler.step(A_ , A_ , A_ ).prev_sample assert sample.dtype == torch.floataa
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
_A = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} _A = ['a', 'b', 'c', 'd', 'e'] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =start # add current to visited visited.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __UpperCamelCase =topological_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # if all neighbors visited add current to sort sort.append(SCREAMING_SNAKE_CASE__ ) # if all vertices haven't been visited select a new one to visit if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): for vertice in vertices: if vertice not in visited: __UpperCamelCase =topological_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # return sort return sort if __name__ == "__main__": _A = topological_sort('a', [], []) print(sort)
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'facebook/detr-resnet-50': 'https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json', # See all DETR models at https://huggingface.co/models?filter=detr } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = "detr" UpperCAmelCase__ : Optional[int] = ["past_key_values"] UpperCAmelCase__ : Optional[int] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , A_=True , A_=None , A_=3 , A_=100 , A_=6 , A_=2048 , A_=8 , A_=6 , A_=2048 , A_=8 , A_=0.0 , A_=0.0 , A_=True , A_="relu" , A_=256 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=1.0 , A_=False , A_="sine" , A_="resnet50" , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=1 , A_=1 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __UpperCamelCase =CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(A_ , A_ ): __UpperCamelCase =backbone_config.get('model_type' ) __UpperCamelCase =CONFIG_MAPPING[backbone_model_type] __UpperCamelCase =config_class.from_dict(A_ ) # set timm attributes to None __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =None, None, None __UpperCamelCase =use_timm_backbone __UpperCamelCase =backbone_config __UpperCamelCase =num_channels __UpperCamelCase =num_queries __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =init_xavier_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =encoder_layers __UpperCamelCase =auxiliary_loss __UpperCamelCase =position_embedding_type __UpperCamelCase =backbone __UpperCamelCase =use_pretrained_backbone __UpperCamelCase =dilation # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =mask_loss_coefficient __UpperCamelCase =dice_loss_coefficient __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient super().__init__(is_encoder_decoder=A_ , **A_ ) @property def _a ( self ) -> int: return self.encoder_attention_heads @property def _a ( self ) -> int: return self.d_model @classmethod def _a ( cls , A_ , **A_ ) -> Tuple: return cls(backbone_config=A_ , **A_ ) def _a ( self ) -> Dict[str, any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: __UpperCamelCase =self.backbone_config.to_dict() __UpperCamelCase =self.__class__.model_type return output class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Dict = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def _a ( self ) -> float: return 1E-5 @property def _a ( self ) -> int: return 12
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = ["image_processor", "tokenizer"] UpperCAmelCase__ : Dict = "OwlViTImageProcessor" UpperCAmelCase__ : Union[str, Any] = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self , A_=None , A_=None , **A_ ) -> Tuple: __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.' , A_ , ) __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__(A_ , A_ ) def __call__( self , A_=None , A_=None , A_=None , A_="max_length" , A_="np" , **A_ ) -> str: if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(A_ , A_ ) or (isinstance(A_ , A_ ) and not isinstance(text[0] , A_ )): __UpperCamelCase =[self.tokenizer(A_ , padding=A_ , return_tensors=A_ , **A_ )] elif isinstance(A_ , A_ ) and isinstance(text[0] , A_ ): __UpperCamelCase =[] # Maximum number of queries across batch __UpperCamelCase =max([len(A_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(A_ ) != max_num_queries: __UpperCamelCase =t + [' '] * (max_num_queries - len(A_ )) __UpperCamelCase =self.tokenizer(A_ , padding=A_ , return_tensors=A_ , **A_ ) encodings.append(A_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": __UpperCamelCase =np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __UpperCamelCase =np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp __UpperCamelCase =jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __UpperCamelCase =jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch __UpperCamelCase =torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) __UpperCamelCase =torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf __UpperCamelCase =tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) __UpperCamelCase =tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) __UpperCamelCase =BatchEncoding() __UpperCamelCase =input_ids __UpperCamelCase =attention_mask if query_images is not None: __UpperCamelCase =BatchEncoding() __UpperCamelCase =self.image_processor( A_ , return_tensors=A_ , **A_ ).pixel_values __UpperCamelCase =query_pixel_values if images is not None: __UpperCamelCase =self.image_processor(A_ , return_tensors=A_ , **A_ ) if text is not None and images is not None: __UpperCamelCase =image_features.pixel_values return encoding elif query_images is not None and images is not None: __UpperCamelCase =image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**A_ ) , tensor_type=A_ ) def _a ( self , *A_ , **A_ ) -> Union[str, Any]: return self.image_processor.post_process(*A_ , **A_ ) def _a ( self , *A_ , **A_ ) -> Optional[Any]: return self.image_processor.post_process_object_detection(*A_ , **A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: return self.image_processor.post_process_image_guided_detection(*A_ , **A_ ) def _a ( self , *A_ , **A_ ) -> str: return self.tokenizer.batch_decode(*A_ , **A_ ) def _a ( self , *A_ , **A_ ) -> Any: return self.tokenizer.decode(*A_ , **A_ ) @property def _a ( self ) -> Dict: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , A_ , ) return self.image_processor_class @property def _a ( self ) -> Tuple: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , A_ , ) return self.image_processor
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =20 * np.logaa(SCREAMING_SNAKE_CASE__ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds __UpperCamelCase =get_bounds(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE__ , -2 * pi ) ) plt.show()
62
1
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, ) _A = logging.get_logger(__name__) _A = 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'), ] ) _A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: __UpperCamelCase =model_type_to_module_name(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =importlib.import_module(F'.{module_name}' , 'transformers.models' ) try: return getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(SCREAMING_SNAKE_CASE__ , '__name__' , SCREAMING_SNAKE_CASE__ ) == 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. __UpperCamelCase =importlib.import_module('transformers' ) if hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return None def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, os.PathLike]] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, str]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[bool, str]] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = None , SCREAMING_SNAKE_CASE__ : bool = False , **SCREAMING_SNAKE_CASE__ : Dict , ): __UpperCamelCase =get_file_from_repo( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ , resume_download=SCREAMING_SNAKE_CASE__ , proxies=SCREAMING_SNAKE_CASE__ , use_auth_token=SCREAMING_SNAKE_CASE__ , revision=SCREAMING_SNAKE_CASE__ , local_files_only=SCREAMING_SNAKE_CASE__ , ) 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(SCREAMING_SNAKE_CASE__ , encoding='utf-8' ) as reader: return json.load(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self ) -> Any: 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(A_ ) def _a ( cls , A_ , **A_ ) -> Union[str, Any]: __UpperCamelCase =kwargs.pop('config' , A_ ) __UpperCamelCase =kwargs.pop('trust_remote_code' , A_ ) __UpperCamelCase =True __UpperCamelCase , __UpperCamelCase =ImageProcessingMixin.get_image_processor_dict(A_ , **A_ ) __UpperCamelCase =config_dict.get('image_processor_type' , A_ ) __UpperCamelCase =None if "AutoImageProcessor" in config_dict.get('auto_map' , {} ): __UpperCamelCase =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: __UpperCamelCase =config_dict.pop('feature_extractor_type' , A_ ) 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.' ) __UpperCamelCase =feature_extractor_class.replace('FeatureExtractor' , 'ImageProcessor' ) if "AutoFeatureExtractor" in config_dict.get('auto_map' , {} ): __UpperCamelCase =config_dict['auto_map']['AutoFeatureExtractor'] __UpperCamelCase =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(A_ , A_ ): __UpperCamelCase =AutoConfig.from_pretrained(A_ , **A_ ) # It could be in `config.image_processor_type`` __UpperCamelCase =getattr(A_ , 'image_processor_type' , A_ ) if hasattr(A_ , 'auto_map' ) and "AutoImageProcessor" in config.auto_map: __UpperCamelCase =config.auto_map['AutoImageProcessor'] if image_processor_class is not None: __UpperCamelCase =image_processor_class_from_name(A_ ) __UpperCamelCase =image_processor_auto_map is not None __UpperCamelCase =image_processor_class is not None or type(A_ ) in IMAGE_PROCESSOR_MAPPING __UpperCamelCase =resolve_trust_remote_code( A_ , A_ , A_ , A_ ) if has_remote_code and trust_remote_code: __UpperCamelCase =get_class_from_dynamic_module( A_ , A_ , **A_ ) __UpperCamelCase =kwargs.pop('code_revision' , A_ ) if os.path.isdir(A_ ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(A_ , **A_ ) elif image_processor_class is not None: return image_processor_class.from_dict(A_ , **A_ ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(A_ ) in IMAGE_PROCESSOR_MAPPING: __UpperCamelCase =IMAGE_PROCESSOR_MAPPING[type(A_ )] return image_processor_class.from_dict(A_ , **A_ ) 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 _a ( A_ , A_ ) -> List[str]: IMAGE_PROCESSOR_MAPPING.register(A_ , A_ )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'huggingface/autoformer-tourism-monthly': 'https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : int = "autoformer" UpperCAmelCase__ : List[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers", } def __init__( self , A_ = None , A_ = None , A_ = "student_t" , A_ = "nll" , A_ = 1 , A_ = [1, 2, 3, 4, 5, 6, 7] , A_ = True , A_ = 0 , A_ = 0 , A_ = 0 , A_ = 0 , A_ = None , A_ = None , A_ = 64 , A_ = 2 , A_ = 2 , A_ = 2 , A_ = 2 , A_ = 32 , A_ = 32 , A_ = "gelu" , A_ = 0.1 , A_ = 0.1 , A_ = 0.1 , A_ = 0.1 , A_ = 0.1 , A_ = 100 , A_ = 0.02 , A_ = True , A_=True , A_ = 10 , A_ = 25 , A_ = 3 , **A_ , ) -> Union[str, Any]: # time series specific configuration __UpperCamelCase =prediction_length __UpperCamelCase =context_length if context_length is not None else prediction_length __UpperCamelCase =distribution_output __UpperCamelCase =loss __UpperCamelCase =input_size __UpperCamelCase =num_time_features __UpperCamelCase =lags_sequence __UpperCamelCase =scaling __UpperCamelCase =num_dynamic_real_features __UpperCamelCase =num_static_real_features __UpperCamelCase =num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(A_ ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __UpperCamelCase =cardinality else: __UpperCamelCase =[0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(A_ ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __UpperCamelCase =embedding_dimension else: __UpperCamelCase =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __UpperCamelCase =num_parallel_samples # Transformer architecture configuration __UpperCamelCase =input_size * len(self.lags_sequence ) + self._number_of_features __UpperCamelCase =d_model __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_attention_heads __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =decoder_layers __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =use_cache # Autoformer __UpperCamelCase =label_length __UpperCamelCase =moving_average __UpperCamelCase =autocorrelation_factor super().__init__(is_encoder_decoder=A_ , **A_ ) @property def _a ( self ) -> int: return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( 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_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =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.' )
62
1
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def _a ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase =UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model def _a ( self ) -> Optional[int]: __UpperCamelCase =self.dummy_uncond_unet __UpperCamelCase =KarrasVeScheduler() __UpperCamelCase =KarrasVePipeline(unet=A_ , scheduler=A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(num_inference_steps=2 , generator=A_ , output_type='numpy' ).images __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(num_inference_steps=2 , generator=A_ , output_type='numpy' , return_dict=A_ )[0] __UpperCamelCase =image[0, -3:, -3:, -1] __UpperCamelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase =np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='google/ncsnpp-celebahq-256' __UpperCamelCase =UNetaDModel.from_pretrained(A_ ) __UpperCamelCase =KarrasVeScheduler() __UpperCamelCase =KarrasVePipeline(unet=A_ , scheduler=A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(num_inference_steps=20 , generator=A_ , output_type='numpy' ).images __UpperCamelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCamelCase =np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = {'vocab_file': 'sentencepiece.bpe.model'} _A = { 'vocab_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model' ), }, } _A = { 'moussaKam/mbarthez': 1024, 'moussaKam/barthez': 1024, 'moussaKam/barthez-orangesum-title': 1024, } _A = '▁' class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = VOCAB_FILES_NAMES UpperCAmelCase__ : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : List[Any] = ["input_ids", "attention_mask"] def __init__( self , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) __UpperCamelCase ={'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} __UpperCamelCase =len(self.sp_model ) - 1 __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[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] @property def _a ( self ) -> Optional[Any]: return len(self.sp_model ) def _a ( self ) -> Dict: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> Union[str, Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __UpperCamelCase =self.sp_model.PieceToId(A_ ) return spm_id if spm_id else self.unk_token_id def _a ( self , A_ ) -> Union[str, Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(A_ ) def _a ( self , A_ ) -> Dict: __UpperCamelCase =[] __UpperCamelCase ='' __UpperCamelCase =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A_ ) + token __UpperCamelCase =True __UpperCamelCase =[] else: current_sub_tokens.append(A_ ) __UpperCamelCase =False out_string += self.sp_model.decode(A_ ) return out_string.strip() def __getstate__( self ) -> int: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None return state def __setstate__( self , A_ ) -> str: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
from heapq import heappop, heappush import numpy as np def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : bool , ): __UpperCamelCase , __UpperCamelCase =grid.shape __UpperCamelCase =[-1, 1, 0, 0] __UpperCamelCase =[0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __UpperCamelCase , __UpperCamelCase =[(0, source)], set() __UpperCamelCase =np.full((rows, cols) , np.inf ) __UpperCamelCase =0 __UpperCamelCase =np.empty((rows, cols) , dtype=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =None while queue: ((__UpperCamelCase) , (__UpperCamelCase)) =heappop(SCREAMING_SNAKE_CASE__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __UpperCamelCase =[] while (x, y) != source: path.append((x, y) ) __UpperCamelCase , __UpperCamelCase =predecessors[x, y] path.append(SCREAMING_SNAKE_CASE__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase , __UpperCamelCase =x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __UpperCamelCase =grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(SCREAMING_SNAKE_CASE__ , (dist + 1, (nx, ny)) ) __UpperCamelCase =dist + 1 __UpperCamelCase =(x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
import math def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =F'Input value of [number={number}] must be an integer' raise TypeError(SCREAMING_SNAKE_CASE__ ) if number < 1: __UpperCamelCase =F'Input value of [number={number}] must be > 0' raise ValueError(SCREAMING_SNAKE_CASE__ ) elif number == 1: return 3 elif number == 2: return 5 else: __UpperCamelCase =int(math.log(number // 3 , 2 ) ) + 2 __UpperCamelCase =[3, 5] __UpperCamelCase =2 __UpperCamelCase =3 for block in range(1 , SCREAMING_SNAKE_CASE__ ): for _ in range(SCREAMING_SNAKE_CASE__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): _A = 0 try: _A = proth(number) except ValueError: print(f"""ValueError: there is no {number}th Proth number""") continue print(f"""The {number}th Proth number: {value}""")
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[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] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _A = 111_4112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _A = 0 _A = 0xe_0_0_0 _A = 0xe_0_0_1 _A = 0xe_0_0_2 _A = 0xe_0_0_3 _A = 0xe_0_0_4 # Maps special codepoints to human-readable names. _A = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _A = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , A_=chr(A_ ) , A_=chr(A_ ) , A_=chr(A_ ) , A_=chr(A_ ) , A_=chr(A_ ) , A_=chr(A_ ) , A_=False , A_=2048 , **A_ , ) -> str: __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else bos_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else eos_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else sep_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else cls_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token super().__init__( bos_token=A_ , eos_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , add_prefix_space=A_ , model_max_length=A_ , **A_ , ) # Creates a mapping for looking up the IDs of special symbols. __UpperCamelCase ={} for codepoint, name in SPECIAL_CODEPOINTS.items(): __UpperCamelCase =codepoint # Creates a mapping for looking up the string forms of special symbol IDs. __UpperCamelCase ={ codepoint: name for name, codepoint in self._special_codepoints.items() } __UpperCamelCase =UNICODE_VOCAB_SIZE __UpperCamelCase =len(self._special_codepoints ) @property def _a ( self ) -> int: return self._unicode_vocab_size def _a ( self , A_ ) -> List[str]: return list(A_ ) def _a ( self , A_ ) -> int: try: return ord(A_ ) except TypeError: raise ValueError(f'invalid token: \'{token}\'' ) def _a ( self , A_ ) -> str: try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(A_ ) except TypeError: raise ValueError(f'invalid id: {index}' ) def _a ( self , A_ ) -> List[str]: return "".join(A_ ) def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) __UpperCamelCase =[1] + ([0] * len(A_ )) + [1] if token_ids_a is not None: result += ([0] * len(A_ )) + [1] return result def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _a ( self , A_ , A_ = None ) -> List[Any]: return ()
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
import cva import numpy as np class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ ) -> Optional[Any]: if k in (0.04, 0.06): __UpperCamelCase =k __UpperCamelCase =window_size else: raise ValueError('invalid k value' ) def __str__( self ) -> str: return str(self.k ) def _a ( self , A_ ) -> tuple[cva.Mat, list[list[int]]]: __UpperCamelCase =cva.imread(A_ , 0 ) __UpperCamelCase , __UpperCamelCase =img.shape __UpperCamelCase =[] __UpperCamelCase =img.copy() __UpperCamelCase =cva.cvtColor(A_ , cva.COLOR_GRAY2RGB ) __UpperCamelCase , __UpperCamelCase =np.gradient(A_ ) __UpperCamelCase =dx**2 __UpperCamelCase =dy**2 __UpperCamelCase =dx * dy __UpperCamelCase =0.04 __UpperCamelCase =self.window_size // 2 for y in range(A_ , h - offset ): for x in range(A_ , w - offset ): __UpperCamelCase =ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __UpperCamelCase =iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __UpperCamelCase =ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __UpperCamelCase =(wxx * wyy) - (wxy**2) __UpperCamelCase =wxx + wyy __UpperCamelCase =det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": _A = HarrisCorner(0.04, 3) _A , _A = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
62
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ) -> PIL.Image.Image: __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(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =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.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness _A = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' _A = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' _A = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' _A = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' _A = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase__ ( datasets.Metric ): """simple docstring""" def _a ( self ) -> Union[str, Any]: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' ) ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/openai/human-eval' , codebase_urls=['https://github.com/openai/human-eval'] , reference_urls=['https://github.com/openai/human-eval'] , license=_LICENSE , ) def _a ( self , A_ , A_ , A_=[1, 10, 100] , A_=4 , A_=3.0 ) -> str: if os.getenv('HF_ALLOW_CODE_EVAL' , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError('This metric is currently not supported on Windows.' ) with ThreadPoolExecutor(max_workers=A_ ) as executor: __UpperCamelCase =[] __UpperCamelCase =Counter() __UpperCamelCase =0 __UpperCamelCase =defaultdict(A_ ) for task_id, (candidates, test_case) in enumerate(zip(A_ , A_ ) ): for candidate in candidates: __UpperCamelCase =candidate + '\n' + test_case __UpperCamelCase =(test_program, timeout, task_id, completion_id[task_id]) __UpperCamelCase =executor.submit(A_ , *A_ ) futures.append(A_ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(A_ ): __UpperCamelCase =future.result() results[result["task_id"]].append((result['completion_id'], result) ) __UpperCamelCase , __UpperCamelCase =[], [] for result in results.values(): result.sort() __UpperCamelCase =[r[1]['passed'] for r in result] total.append(len(A_ ) ) correct.append(sum(A_ ) ) __UpperCamelCase =np.array(A_ ) __UpperCamelCase =np.array(A_ ) __UpperCamelCase =k __UpperCamelCase ={f'pass@{k}': estimate_pass_at_k(A_ , A_ , A_ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ): def estimator(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =itertools.repeat(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) else: assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =iter(SCREAMING_SNAKE_CASE__ ) return np.array([estimator(int(SCREAMING_SNAKE_CASE__ ) , int(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) for n, c in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] )
62
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 _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
from math import pi def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): return 2 * pi * radius * (angle / 3_60) if __name__ == "__main__": print(arc_length(90, 10))
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _A = logging.get_logger(__name__) _A = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _A = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _A = { 'yjernite/retribert-base-uncased': 512, } _A = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : Dict = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Tuple = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase__ : Optional[int] = RetriBertTokenizer UpperCAmelCase__ : int = ["input_ids", "attention_mask"] def __init__( self , A_=None , A_=None , A_=True , A_="[UNK]" , A_="[SEP]" , A_="[PAD]" , A_="[CLS]" , A_="[MASK]" , A_=True , A_=None , **A_ , ) -> Any: super().__init__( A_ , tokenizer_file=A_ , do_lower_case=A_ , unk_token=A_ , sep_token=A_ , pad_token=A_ , cls_token=A_ , mask_token=A_ , tokenize_chinese_chars=A_ , strip_accents=A_ , **A_ , ) __UpperCamelCase =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , A_ ) != do_lower_case or normalizer_state.get('strip_accents' , A_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , A_ ) != tokenize_chinese_chars ): __UpperCamelCase =getattr(A_ , normalizer_state.pop('type' ) ) __UpperCamelCase =do_lower_case __UpperCamelCase =strip_accents __UpperCamelCase =tokenize_chinese_chars __UpperCamelCase =normalizer_class(**A_ ) __UpperCamelCase =do_lower_case def _a ( self , A_ , A_=None ) -> Optional[Any]: __UpperCamelCase =[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 _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[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 _a ( self , A_ , A_ = None ) -> Tuple[str]: __UpperCamelCase =self._tokenizer.model.save(A_ , name=A_ ) return tuple(A_ )
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
import argparse import json import subprocess def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ): __UpperCamelCase =[] __UpperCamelCase =( F'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"' ' https://api.github.com/repos/huggingface/transformers/actions/runners' ) __UpperCamelCase =subprocess.run(SCREAMING_SNAKE_CASE__ , shell=SCREAMING_SNAKE_CASE__ , stdout=subprocess.PIPE ) __UpperCamelCase =output.stdout.decode('utf-8' ) __UpperCamelCase =json.loads(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =status['runners'] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(SCREAMING_SNAKE_CASE__ ) # save the result so we can report them on Slack with open('offline_runners.txt' , 'w' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) > 0: __UpperCamelCase ='\n'.join([x['name'] for x in offline_runners] ) raise ValueError(F'The following runners are offline:\n{failed}' ) if __name__ == "__main__": def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): return values.split(',' ) _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--target_runners', default=None, type=list_str, required=True, help='Comma-separated list of runners to check status.', ) parser.add_argument( '--token', default=None, type=str, required=True, help='A token that has actions:read permission.' ) _A = parser.parse_args() get_runner_status(args.target_runners, args.token)
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
from collections.abc import Iterable from typing import Generic, TypeVar _A = TypeVar('_T') class UpperCAmelCase__ ( Generic[_T] ): """simple docstring""" def __init__( self , A_ = None ) -> None: __UpperCamelCase =list(iterable or [] ) __UpperCamelCase =[] def __len__( self ) -> int: return len(self._stacka ) + len(self._stacka ) def __repr__( self ) -> str: return f'Queue({tuple(self._stacka[::-1] + self._stacka )})' def _a ( self , A_ ) -> None: self._stacka.append(A_ ) def _a ( self ) -> _T: __UpperCamelCase =self._stacka.pop __UpperCamelCase =self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError('Queue is empty' ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device 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 ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=False , A_=True , A_="None" , A_=3 , A_=4 , A_=None , ) -> Optional[int]: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =seq_length __UpperCamelCase =is_training __UpperCamelCase =use_input_mask __UpperCamelCase =use_token_type_ids __UpperCamelCase =use_labels __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =type_vocab_size __UpperCamelCase =type_sequence_label_size __UpperCamelCase =initializer_range __UpperCamelCase =num_labels __UpperCamelCase =num_choices __UpperCamelCase =relative_attention __UpperCamelCase =position_biased_input __UpperCamelCase =pos_att_type __UpperCamelCase =scope def _a ( self ) -> List[Any]: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase =None if self.use_input_mask: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __UpperCamelCase =None if self.use_token_type_ids: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase =ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> str: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def _a ( self , A_ ) -> Tuple: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Tuple: __UpperCamelCase =DebertaVaModel(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , token_type_ids=A_ )[0] __UpperCamelCase =model(A_ , token_type_ids=A_ )[0] __UpperCamelCase =model(A_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Optional[Any]: __UpperCamelCase =DebertaVaForMaskedLM(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Dict: __UpperCamelCase =self.num_labels __UpperCamelCase =DebertaVaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(A_ ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> List[Any]: __UpperCamelCase =self.num_labels __UpperCamelCase =DebertaVaForTokenClassification(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Any: __UpperCamelCase =DebertaVaForQuestionAnswering(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model( A_ , attention_mask=A_ , token_type_ids=A_ , start_positions=A_ , end_positions=A_ , ) 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 _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> int: __UpperCamelCase =DebertaVaForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase =model( A_ , attention_mask=A_ , token_type_ids=A_ , labels=A_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) =config_and_inputs __UpperCamelCase ={'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""" UpperCAmelCase__ : Dict = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) UpperCAmelCase__ : Union[str, Any] = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : int = False UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : List[str] = False def _a ( self ) -> Optional[int]: __UpperCamelCase =DebertaVaModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , hidden_size=37 ) def _a ( self ) -> Dict: self.config_tester.run_common_tests() def _a ( self ) -> str: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*A_ ) def _a ( self ) -> List[str]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*A_ ) def _a ( self ) -> Any: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*A_ ) def _a ( self ) -> str: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*A_ ) def _a ( self ) -> List[str]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*A_ ) @slow def _a ( self ) -> Tuple: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase =DebertaVaModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason='Model not available yet' ) def _a ( self ) -> int: pass @slow def _a ( self ) -> Tuple: __UpperCamelCase =DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __UpperCamelCase =torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) __UpperCamelCase =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __UpperCamelCase =model(A_ , attention_mask=A_ )[0] # compare the actual values for a slice. __UpperCamelCase =torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , A_ , atol=1E-4 ) , f'{output[:, 1:4, 1:4]}' )
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["keras_nlp"] def __init__( self , *A_ , **A_ ) -> Tuple: requires_backends(self , ['keras_nlp'] )
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =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] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> str: __UpperCamelCase =tempfile.mkdtemp() # fmt: off __UpperCamelCase =['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) __UpperCamelCase ={ 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073], 'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711], } __UpperCamelCase =os.path.join(self.tmpdirname , A_ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(A_ , A_ ) def _a ( self , **A_ ) -> List[Any]: return CLIPTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Any: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **A_ ) def _a ( self ) -> Any: shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Tuple: __UpperCamelCase =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __UpperCamelCase =[Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase =self.get_image_processor() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) processor_slow.save_pretrained(self.tmpdirname ) __UpperCamelCase =CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=A_ ) __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) processor_fast.save_pretrained(self.tmpdirname ) __UpperCamelCase =CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , A_ ) self.assertIsInstance(processor_fast.tokenizer , A_ ) 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 , A_ ) self.assertIsInstance(processor_fast.image_processor , A_ ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __UpperCamelCase =self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __UpperCamelCase =self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __UpperCamelCase =CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=A_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , A_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =image_processor(A_ , return_tensors='np' ) __UpperCamelCase =processor(images=A_ , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase ='lower newer' __UpperCamelCase =processor(text=A_ ) __UpperCamelCase =tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _a ( self ) -> List[Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase ='lower newer' __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(A_ ): processor() def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __UpperCamelCase =processor.batch_decode(A_ ) __UpperCamelCase =tokenizer.batch_decode(A_ ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =CLIPProcessor(tokenizer=A_ , image_processor=A_ ) __UpperCamelCase ='lower newer' __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =processor(text=A_ , images=A_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_lxmert': ['LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LxmertConfig'], 'tokenization_lxmert': ['LxmertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['LxmertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'LxmertEncoder', 'LxmertForPreTraining', 'LxmertForQuestionAnswering', 'LxmertModel', 'LxmertPreTrainedModel', 'LxmertVisualFeatureEncoder', 'LxmertXLayer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLxmertForPreTraining', 'TFLxmertMainLayer', 'TFLxmertModel', 'TFLxmertPreTrainedModel', 'TFLxmertVisualFeatureEncoder', ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from __future__ import annotations from collections.abc import Generator def _UpperCAmelCase ( ): __UpperCamelCase ={} __UpperCamelCase =2 while True: __UpperCamelCase =factor_map.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if factor: __UpperCamelCase =factor + prime while x in factor_map: x += factor __UpperCamelCase =factor else: __UpperCamelCase =prime yield prime prime += 1 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float = 1E10 ): __UpperCamelCase =sieve() __UpperCamelCase =1 while True: __UpperCamelCase =next(SCREAMING_SNAKE_CASE__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(SCREAMING_SNAKE_CASE__ ) n += 2 if __name__ == "__main__": print(solution())
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> List[Any]: __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =SamImageProcessor() __UpperCamelCase =SamProcessor(A_ ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **A_ ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **A_ ).image_processor def _a ( self ) -> Any: shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Tuple: __UpperCamelCase =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __UpperCamelCase =[Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> List[str]: __UpperCamelCase =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __UpperCamelCase =self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __UpperCamelCase =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=A_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def _a ( self ) -> str: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =SamProcessor(image_processor=A_ ) __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =image_processor(A_ , return_tensors='np' ) __UpperCamelCase =processor(images=A_ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =SamProcessor(image_processor=A_ ) __UpperCamelCase =[torch.ones((1, 3, 5, 5) )] __UpperCamelCase =[[1764, 2646]] __UpperCamelCase =[[683, 1024]] __UpperCamelCase =processor.post_process_masks(A_ , A_ , A_ ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __UpperCamelCase =processor.post_process_masks( A_ , torch.tensor(A_ ) , torch.tensor(A_ ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __UpperCamelCase =[np.ones((1, 3, 5, 5) )] __UpperCamelCase =processor.post_process_masks(A_ , np.array(A_ ) , np.array(A_ ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __UpperCamelCase =[[1, 0], [0, 1]] with self.assertRaises(A_ ): __UpperCamelCase =processor.post_process_masks(A_ , np.array(A_ ) , np.array(A_ ) ) @require_vision @require_tf class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Any: __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =SamImageProcessor() __UpperCamelCase =SamProcessor(A_ ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **A_ ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **A_ ).image_processor def _a ( self ) -> Tuple: shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Any: __UpperCamelCase =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __UpperCamelCase =[Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Optional[int]: __UpperCamelCase =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __UpperCamelCase =self.get_image_processor(do_normalize=A_ , padding_value=1.0 ) __UpperCamelCase =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=A_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A_ ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =SamProcessor(image_processor=A_ ) __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =image_processor(A_ , return_tensors='np' ) __UpperCamelCase =processor(images=A_ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> str: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =SamProcessor(image_processor=A_ ) __UpperCamelCase =[tf.ones((1, 3, 5, 5) )] __UpperCamelCase =[[1764, 2646]] __UpperCamelCase =[[683, 1024]] __UpperCamelCase =processor.post_process_masks(A_ , A_ , A_ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __UpperCamelCase =processor.post_process_masks( A_ , tf.convert_to_tensor(A_ ) , tf.convert_to_tensor(A_ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __UpperCamelCase =[np.ones((1, 3, 5, 5) )] __UpperCamelCase =processor.post_process_masks( A_ , np.array(A_ ) , np.array(A_ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __UpperCamelCase =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __UpperCamelCase =processor.post_process_masks( A_ , np.array(A_ ) , np.array(A_ ) , return_tensors='tf' ) @require_vision @require_torchvision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Any: __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =SamImageProcessor() __UpperCamelCase =SamProcessor(A_ ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **A_ ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **A_ ).image_processor def _a ( self ) -> Optional[Any]: shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: __UpperCamelCase =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __UpperCamelCase =[Image.fromarray(np.moveaxis(A_ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Dict: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =SamProcessor(image_processor=A_ ) __UpperCamelCase =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __UpperCamelCase =[tf.convert_to_tensor(A_ )] __UpperCamelCase =[torch.tensor(A_ )] __UpperCamelCase =[[1764, 2646]] __UpperCamelCase =[[683, 1024]] __UpperCamelCase =processor.post_process_masks( A_ , A_ , A_ , return_tensors='tf' ) __UpperCamelCase =processor.post_process_masks( A_ , A_ , A_ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_image_processor() __UpperCamelCase =SamProcessor(image_processor=A_ ) __UpperCamelCase =self.prepare_image_inputs() __UpperCamelCase =image_processor(A_ , return_tensors='pt' )['pixel_values'].numpy() __UpperCamelCase =processor(images=A_ , return_tensors='pt' )['pixel_values'].numpy() __UpperCamelCase =image_processor(A_ , return_tensors='tf' )['pixel_values'].numpy() __UpperCamelCase =processor(images=A_ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(A_ , A_ ) ) self.assertTrue(np.allclose(A_ , A_ ) ) self.assertTrue(np.allclose(A_ , A_ ) )
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from collections.abc import Generator def _UpperCAmelCase ( ): __UpperCamelCase , __UpperCamelCase =0, 1 while True: __UpperCamelCase , __UpperCamelCase =b, a + b yield b def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10_00 ): __UpperCamelCase =1 __UpperCamelCase =fibonacci_generator() while len(str(next(SCREAMING_SNAKE_CASE__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =20 * np.logaa(SCREAMING_SNAKE_CASE__ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds __UpperCamelCase =get_bounds(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(SCREAMING_SNAKE_CASE__ ) plt.show() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.angle(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE__ , -2 * pi ) ) plt.show()
62
1
import os def _UpperCAmelCase ( ): __UpperCamelCase =os.path.dirname(os.path.realpath(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , 'triangle.txt' ) with open(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.readlines() __UpperCamelCase =[] for line in triangle: __UpperCamelCase =[] for number in line.strip().split(' ' ): numbers_from_line.append(int(SCREAMING_SNAKE_CASE__ ) ) a.append(SCREAMING_SNAKE_CASE__ ) for i in range(1 , len(SCREAMING_SNAKE_CASE__ ) ): for j in range(len(a[i] ) ): __UpperCamelCase =a[i - 1][j] if j != len(a[i - 1] ) else 0 __UpperCamelCase =a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( 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_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =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.' )
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): return int((input_a, input_a).count(0 ) == 0 ) def _UpperCAmelCase ( ): assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever _A = logging.getLogger(__name__) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ , A_ , A_=None ) -> List[str]: super().__init__( A_ , question_encoder_tokenizer=A_ , generator_tokenizer=A_ , index=A_ , init_retrieval=A_ , ) __UpperCamelCase =None def _a ( self , A_ ) -> Any: logger.info('initializing retrieval' ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info('dist initialized' ) # needs to be set manually __UpperCamelCase =self._infer_socket_ifname() # avoid clash with the NCCL port __UpperCamelCase =str(distributed_port + 1 ) __UpperCamelCase =dist.new_group(ranks=A_ , backend='gloo' ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info('dist not initialized / main' ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def _a ( self ) -> List[str]: return dist.get_rank(group=self.process_group ) == 0 def _a ( self , A_ , A_ , A_=torch.floataa ) -> Tuple: __UpperCamelCase =torch.empty(A_ , dtype=A_ ) dist.scatter(A_ , src=0 , scatter_list=A_ , group=self.process_group ) return target_tensor def _a ( self ) -> Dict: __UpperCamelCase =psutil.net_if_addrs() # a hacky way to deal with varying network interface names __UpperCamelCase =next((addr for addr in addrs if addr.startswith('e' )) , A_ ) return ifname def _a ( self , A_ , A_ ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): __UpperCamelCase , __UpperCamelCase =self._main_retrieve(A_ , A_ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A_ ) # distributed training __UpperCamelCase =dist.get_world_size(group=self.process_group ) # gather logic __UpperCamelCase =None if self._is_main(): __UpperCamelCase =[torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(A_ )] dist.gather(torch.tensor(A_ ) , dst=0 , gather_list=A_ , group=self.process_group ) # scatter logic __UpperCamelCase =question_hidden_states.shape[0] __UpperCamelCase =[] __UpperCamelCase =[] if self._is_main(): assert len(A_ ) == world_size __UpperCamelCase , __UpperCamelCase =self._main_retrieve(torch.cat(A_ ).numpy() , A_ ) __UpperCamelCase , __UpperCamelCase =torch.tensor(A_ ), torch.tensor(A_ ) __UpperCamelCase =self._chunk_tensor(A_ , A_ ) __UpperCamelCase =self._chunk_tensor(A_ , A_ ) __UpperCamelCase =self._scattered(A_ , [n_queries, n_docs] , target_type=torch.intaa ) __UpperCamelCase =self._scattered(A_ , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(A_ )
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _A = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1