code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version snake_case_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt') def lowerCamelCase__ ( snake_case_ : np.ndarray , snake_case_ : float , snake_case_ : int = 1_6000 ) -> str: __snake_case = int(round(sample_rate * max_length ) ) if len(snake_case_ ) <= sample_length: return wav __snake_case = randint(0 , len(snake_case_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class SCREAMING_SNAKE_CASE__ : A_ : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'Name of a dataset from the datasets package'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'A file containing the training audio paths and labels.'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'A file containing the validation audio paths and labels.'} ) A_ : str = field( default='train' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) A_ : str = field( default='validation' , metadata={ 'help': ( 'The name of the training data set split to use (via the datasets library). Defaults to \'validation\'' ) } , ) A_ : str = field( default='audio' , metadata={'help': 'The name of the dataset column containing the audio data. Defaults to \'audio\''} , ) A_ : str = field( default='label' , metadata={'help': 'The name of the dataset column containing the labels. Defaults to \'label\''} ) A_ : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A_ : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) A_ : float = field( default=20 , metadata={'help': 'Audio clips will be randomly cut to this length during training if the value is set.'} , ) @dataclass class SCREAMING_SNAKE_CASE__ : A_ : str = field( default='facebook/wav2vec2-base' , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from the Hub'} ) A_ : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Name or path of preprocessor config.'} ) A_ : bool = field( default=_UpperCAmelCase , metadata={'help': 'Whether to freeze the feature encoder layers of the model.'} ) A_ : bool = field( default=_UpperCAmelCase , metadata={'help': 'Whether to generate an attention mask in the feature extractor.'} ) A_ : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A_ : Optional[bool] = field( default=_UpperCAmelCase , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) A_ : bool = field( default=_UpperCAmelCase , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , ) def a (self : int ): """simple docstring""" if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , lowerCAmelCase__ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def lowerCamelCase__ ( ) -> List[str]: __snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __snake_case , __snake_case , __snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case , __snake_case , __snake_case = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' , snake_case_ , snake_case_ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __snake_case = training_args.get_process_log_level() logger.setLevel(snake_case_ ) transformers.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """ + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. __snake_case = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __snake_case = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. __snake_case = DatasetDict() __snake_case = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) __snake_case = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """ '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' f"""{', '.join(raw_datasets['train'].column_names )}.""" ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( f"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """ '''Make sure to set `--label_column_name` to the correct text column - one of ''' f"""{', '.join(raw_datasets['train'].column_names )}.""" ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy __snake_case = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. __snake_case = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) __snake_case = feature_extractor.model_input_names[0] def train_transforms(snake_case_ : Dict ): __snake_case = [] for audio in batch[data_args.audio_column_name]: __snake_case = random_subsample( audio['''array'''] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(snake_case_ ) __snake_case = feature_extractor(snake_case_ , sampling_rate=feature_extractor.sampling_rate ) __snake_case = {model_input_name: inputs.get(snake_case_ )} __snake_case = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(snake_case_ : List[Any] ): __snake_case = [audio['''array'''] for audio in batch[data_args.audio_column_name]] __snake_case = feature_extractor(snake_case_ , sampling_rate=feature_extractor.sampling_rate ) __snake_case = {model_input_name: inputs.get(snake_case_ )} __snake_case = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. __snake_case = raw_datasets['''train'''].features[data_args.label_column_name].names __snake_case , __snake_case = {}, {} for i, label in enumerate(snake_case_ ): __snake_case = str(snake_case_ ) __snake_case = label # Load the accuracy metric from the datasets package __snake_case = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(snake_case_ : Dict ): __snake_case = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=snake_case_ , references=eval_pred.label_ids ) __snake_case = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(snake_case_ ) , labelaid=snake_case_ , idalabel=snake_case_ , finetuning_task='''audio-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __snake_case = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: __snake_case = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(snake_case_ , output_all_columns=snake_case_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: __snake_case = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(snake_case_ , output_all_columns=snake_case_ ) # Initialize our trainer __snake_case = Trainer( model=snake_case_ , args=snake_case_ , train_dataset=raw_datasets['''train'''] if training_args.do_train else None , eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None , compute_metrics=snake_case_ , tokenizer=snake_case_ , ) # Training if training_args.do_train: __snake_case = None if training_args.resume_from_checkpoint is not None: __snake_case = training_args.resume_from_checkpoint elif last_checkpoint is not None: __snake_case = last_checkpoint __snake_case = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __snake_case = trainer.evaluate() trainer.log_metrics('''eval''' , snake_case_ ) trainer.save_metrics('''eval''' , snake_case_ ) # Write model card and (optionally) push to hub __snake_case = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**snake_case_ ) else: trainer.create_model_card(**snake_case_ ) if __name__ == "__main__": main()
592
'''simple docstring''' from __future__ import annotations import queue class __lowerCAmelCase : """simple docstring""" def __init__( self : str , lowerCAmelCase__ : Optional[int] ) -> str: '''simple docstring''' _UpperCamelCase = data _UpperCamelCase = None _UpperCamelCase = None def a__ ( ) -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) _UpperCamelCase = input('''Enter the value of the root node: ''' ).strip().lower() _UpperCamelCase = queue.Queue() _UpperCamelCase = TreeNode(int(lowercase ) ) q.put(lowercase ) while not q.empty(): _UpperCamelCase = q.get() _UpperCamelCase = F"""Enter the left node of {node_found.data}: """ _UpperCamelCase = input(lowercase ).strip().lower() or '''n''' if check == "n": return tree_node _UpperCamelCase = TreeNode(int(lowercase ) ) _UpperCamelCase = left_node q.put(lowercase ) _UpperCamelCase = F"""Enter the right node of {node_found.data}: """ _UpperCamelCase = input(lowercase ).strip().lower() or '''n''' if check == "n": return tree_node _UpperCamelCase = TreeNode(int(lowercase ) ) _UpperCamelCase = right_node q.put(lowercase ) raise def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return print(node.data, end=''',''' ) pre_order(node.left ) pre_order(node.right ) def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return in_order(node.left ) print(node.data, end=''',''' ) in_order(node.right ) def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data, end=''',''' ) def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return _UpperCamelCase = queue.Queue() q.put(lowercase ) while not q.empty(): _UpperCamelCase = q.get() print(node_dequeued.data, end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return _UpperCamelCase = queue.Queue() q.put(lowercase ) while not q.empty(): _UpperCamelCase = [] while not q.empty(): _UpperCamelCase = q.get() print(node_dequeued.data, end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(lowercase ) def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return _UpperCamelCase = [] _UpperCamelCase = node while n or stack: while n: # start from root node, find its left child print(n.data, end=''',''' ) stack.append(lowercase ) _UpperCamelCase = n.left # end of while means current node doesn't have left child _UpperCamelCase = stack.pop() # start to traverse its right child _UpperCamelCase = n.right def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return _UpperCamelCase = [] _UpperCamelCase = node while n or stack: while n: stack.append(lowercase ) _UpperCamelCase = n.left _UpperCamelCase = stack.pop() print(n.data, end=''',''' ) _UpperCamelCase = n.right def a__ ( lowercase : TreeNode ) -> None: """simple docstring""" if not isinstance(lowercase, lowercase ) or not node: return _UpperCamelCase , _UpperCamelCase = [], [] _UpperCamelCase = node stacka.append(lowercase ) while stacka: # to find the reversed order of post order, store it in stack2 _UpperCamelCase = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(lowercase ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data, end=''',''' ) def a__ ( lowercase : str = "", lowercase : List[str]=50, lowercase : List[str]="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char _UpperCamelCase , _UpperCamelCase = divmod(width - len(lowercase ) - 2, 2 ) return F"""{left * char} {s} {(left + extra) * char}""" if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) lowercase__ : TreeNode = build_tree() print(prompt('Pre Order Traversal')) pre_order(node) print(prompt() + '\n') print(prompt('In Order Traversal')) in_order(node) print(prompt() + '\n') print(prompt('Post Order Traversal')) post_order(node) print(prompt() + '\n') print(prompt('Level Order Traversal')) level_order(node) print(prompt() + '\n') print(prompt('Actual Level Order Traversal')) level_order_actual(node) print('*' * 50 + '\n') print(prompt('Pre Order Traversal - Iteration Version')) pre_order_iter(node) print(prompt() + '\n') print(prompt('In Order Traversal - Iteration Version')) in_order_iter(node) print(prompt() + '\n') print(prompt('Post Order Traversal - Iteration Version')) post_order_iter(node) print(prompt())
98
0
import os __magic_name__ : List[Any] = {'I': 1, 'V': 5, 'X': 1_0, 'L': 5_0, 'C': 1_0_0, 'D': 5_0_0, 'M': 1_0_0_0} def lowerCAmelCase ( snake_case__ : str )-> int: A_ = 0 A_ = 0 while index < len(snake_case__ ) - 1: A_ = SYMBOLS[numerals[index]] A_ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def lowerCAmelCase ( snake_case__ : int )-> str: A_ = "" A_ = num // 1000 numerals += m_count * "M" num %= 1000 A_ = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 A_ = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def lowerCAmelCase ( snake_case__ : str = "/p089_roman.txt" )-> int: A_ = 0 with open(os.path.dirname(snake_case__ ) + roman_numerals_filename ) as filea: A_ = filea.readlines() for line in lines: A_ = line.strip() A_ = parse_roman_numerals(snake_case__ ) A_ = generate_roman_numerals(snake_case__ ) savings += len(snake_case__ ) - len(snake_case__ ) return savings if __name__ == "__main__": print(f"""{solution() = }""")
608
from __future__ import annotations from math import pi, sqrt def lowerCAmelCase ( snake_case__ : float , snake_case__ : float )-> tuple: if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative" ) elif capacitance <= 0: raise ValueError("Capacitance cannot be 0 or negative" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
608
1
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class a ( __lowerCamelCase ): def __lowerCamelCase ( self :str ): snake_case__ : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCamelCase_ ,'''tf_padding''' ) ) self.parent.assertTrue(hasattr(UpperCamelCase_ ,'''depth_multiplier''' ) ) class a : def __init__( self :int ,__lowercase :int ,__lowercase :Dict=1_3 ,__lowercase :List[Any]=3 ,__lowercase :List[Any]=3_2 ,__lowercase :int=0.25 ,__lowercase :Tuple=8 ,__lowercase :List[str]=8 ,__lowercase :List[str]=6 ,__lowercase :str=3_2 ,__lowercase :Any=True ,__lowercase :int=True ,__lowercase :List[Any]=True ,__lowercase :str="relu6" ,__lowercase :Union[str, Any]=1_2_8_0 ,__lowercase :List[str]=0.1 ,__lowercase :str=0.02 ,__lowercase :Optional[int]=True ,__lowercase :Union[str, Any]=True ,__lowercase :List[str]=1_0 ,__lowercase :Dict=None ,): snake_case__ : Optional[Any] = parent snake_case__ : Tuple = batch_size snake_case__ : Any = num_channels snake_case__ : Optional[Any] = image_size snake_case__ : List[str] = depth_multiplier snake_case__ : Tuple = depth_divisible_by snake_case__ : Tuple = min_depth snake_case__ : str = expand_ratio snake_case__ : List[str] = tf_padding snake_case__ : Any = output_stride snake_case__ : Optional[int] = first_layer_is_expansion snake_case__ : str = finegrained_output snake_case__ : int = hidden_act snake_case__ : Union[str, Any] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) snake_case__ : Union[str, Any] = classifier_dropout_prob snake_case__ : str = use_labels snake_case__ : int = is_training snake_case__ : Any = num_labels snake_case__ : Optional[Any] = initializer_range snake_case__ : Tuple = scope def __lowerCamelCase ( self :Tuple ): snake_case__ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : Any = None snake_case__ : Optional[Any] = None if self.use_labels: snake_case__ : List[str] = ids_tensor([self.batch_size] ,self.num_labels ) snake_case__ : Optional[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) snake_case__ : Union[str, Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __lowerCamelCase ( self :Tuple ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,depth_divisible_by=self.depth_divisible_by ,min_depth=self.min_depth ,expand_ratio=self.expand_ratio ,output_stride=self.output_stride ,first_layer_is_expansion=self.first_layer_is_expansion ,finegrained_output=self.finegrained_output ,hidden_act=self.hidden_act ,tf_padding=self.tf_padding ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def __lowerCamelCase ( self :Optional[Any] ,__lowercase :str ,__lowercase :List[str] ,__lowercase :Any ,__lowercase :str ): snake_case__ : List[Any] = MobileNetVaModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() snake_case__ : Optional[int] = model(UpperCamelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) self.parent.assertEqual( result.pooler_output.shape ,(self.batch_size, self.last_hidden_size) ,) def __lowerCamelCase ( self :List[Any] ,__lowercase :List[str] ,__lowercase :List[str] ,__lowercase :List[Any] ,__lowercase :Dict ): snake_case__ : Tuple = self.num_labels snake_case__ : Optional[Any] = MobileNetVaForImageClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() snake_case__ : Any = model(UpperCamelCase_ ,labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowerCamelCase ( self :Optional[int] ,__lowercase :List[str] ,__lowercase :str ,__lowercase :Union[str, Any] ,__lowercase :Dict ): snake_case__ : int = self.num_labels snake_case__ : Dict = MobileNetVaForSemanticSegmentation(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() snake_case__ : str = model(UpperCamelCase_ ) self.parent.assertEqual( result.logits.shape ,( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) snake_case__ : int = model(UpperCamelCase_ ,labels=UpperCamelCase_ ) self.parent.assertEqual( result.logits.shape ,( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def __lowerCamelCase ( self :Union[str, Any] ): snake_case__ : Union[str, Any] = self.prepare_config_and_inputs() snake_case__ : str = config_and_inputs snake_case__ : List[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): __lowerCAmelCase : Dict = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) __lowerCAmelCase : List[str] = ( { "feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification, "image-segmentation": MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) __lowerCAmelCase : Optional[Any] = False __lowerCAmelCase : Union[str, Any] = False __lowerCAmelCase : Optional[int] = False __lowerCAmelCase : Optional[int] = False def __lowerCamelCase ( self :List[str] ): snake_case__ : List[Any] = MobileNetVaModelTester(self ) snake_case__ : Union[str, Any] = MobileNetVaConfigTester(self ,config_class=UpperCamelCase_ ,has_text_modality=UpperCamelCase_ ) def __lowerCamelCase ( self :List[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason='''MobileNetV2 does not use inputs_embeds''' ) def __lowerCamelCase ( self :Any ): pass @unittest.skip(reason='''MobileNetV2 does not support input and output embeddings''' ) def __lowerCamelCase ( self :Any ): pass @unittest.skip(reason='''MobileNetV2 does not output attentions''' ) def __lowerCamelCase ( self :Optional[Any] ): pass def __lowerCamelCase ( self :List[str] ): snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Optional[int] = model_class(UpperCamelCase_ ) snake_case__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Tuple = [*signature.parameters.keys()] snake_case__ : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1] ,UpperCamelCase_ ) def __lowerCamelCase ( self :List[Any] ): snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def __lowerCamelCase ( self :Dict ): def check_hidden_states_output(__lowercase :str ,__lowercase :Tuple ,__lowercase :Union[str, Any] ): snake_case__ : int = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): snake_case__ : Dict = model(**self._prepare_for_class(UpperCamelCase_ ,UpperCamelCase_ ) ) snake_case__ : Tuple = outputs.hidden_states snake_case__ : List[Any] = 1_6 self.assertEqual(len(UpperCamelCase_ ) ,UpperCamelCase_ ) snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Union[str, Any] = True check_hidden_states_output(UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True check_hidden_states_output(UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ) def __lowerCamelCase ( self :Optional[int] ): snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_ ) def __lowerCamelCase ( self :Tuple ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase_ ) @slow def __lowerCamelCase ( self :Union[str, Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : List[str] = MobileNetVaModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" snake_case__ : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class a ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self :Tuple ): return ( MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224''' ) if is_vision_available() else None ) @slow def __lowerCamelCase ( self :int ): snake_case__ : Optional[Any] = MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224''' ).to(UpperCamelCase_ ) snake_case__ : Optional[Any] = self.default_image_processor snake_case__ : Optional[Any] = prepare_img() snake_case__ : Any = image_processor(images=UpperCamelCase_ ,return_tensors='''pt''' ).to(UpperCamelCase_ ) # forward pass with torch.no_grad(): snake_case__ : Tuple = model(**UpperCamelCase_ ) # verify the logits snake_case__ : List[Any] = torch.Size((1, 1_0_0_1) ) self.assertEqual(outputs.logits.shape ,UpperCamelCase_ ) snake_case__ : Optional[int] = torch.tensor([0.2445, -1.1993, 0.1905] ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,UpperCamelCase_ ,atol=1e-4 ) ) @slow def __lowerCamelCase ( self :Optional[int] ): snake_case__ : List[str] = MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' ) snake_case__ : Optional[Any] = model.to(UpperCamelCase_ ) snake_case__ : List[str] = MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' ) snake_case__ : List[str] = prepare_img() snake_case__ : Optional[Any] = image_processor(images=UpperCamelCase_ ,return_tensors='''pt''' ).to(UpperCamelCase_ ) # forward pass with torch.no_grad(): snake_case__ : List[Any] = model(**UpperCamelCase_ ) snake_case__ : Dict = outputs.logits # verify the logits snake_case__ : Dict = torch.Size((1, 2_1, 6_5, 6_5) ) self.assertEqual(logits.shape ,UpperCamelCase_ ) snake_case__ : List[Any] = torch.tensor( [ [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]], [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]], [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]], ] ,device=UpperCamelCase_ ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,UpperCamelCase_ ,atol=1e-4 ) )
252
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging _a : Optional[int] = logging.get_logger(__name__) _a : List[str] = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class __A (__magic_name__ ): snake_case :List[str] = "van" def __init__( self , UpperCamelCase_=2_24 , UpperCamelCase_=3 , UpperCamelCase_=[7, 3, 3, 3] , UpperCamelCase_=[4, 2, 2, 2] , UpperCamelCase_=[64, 1_28, 3_20, 5_12] , UpperCamelCase_=[3, 3, 12, 3] , UpperCamelCase_=[8, 8, 4, 4] , UpperCamelCase_="gelu" , UpperCamelCase_=0.0_2 , UpperCamelCase_=1E-6 , UpperCamelCase_=1E-2 , UpperCamelCase_=0.0 , UpperCamelCase_=0.0 , **UpperCamelCase_ , ): super().__init__(**UpperCamelCase_ ) __UpperCAmelCase : List[Any] = image_size __UpperCAmelCase : Dict = num_channels __UpperCAmelCase : Optional[Any] = patch_sizes __UpperCAmelCase : Tuple = strides __UpperCAmelCase : Any = hidden_sizes __UpperCAmelCase : str = depths __UpperCAmelCase : Optional[Any] = mlp_ratios __UpperCAmelCase : Union[str, Any] = hidden_act __UpperCAmelCase : int = initializer_range __UpperCAmelCase : Dict = layer_norm_eps __UpperCAmelCase : int = layer_scale_init_value __UpperCAmelCase : Optional[int] = drop_path_rate __UpperCAmelCase : str = dropout_rate
168
0
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 YolosImageProcessor class UpperCamelCase__ ( unittest.TestCase ): def __init__(self : Union[str, Any] , snake_case_ : Dict , snake_case_ : Optional[int]=7 , snake_case_ : List[str]=3 , snake_case_ : List[str]=3_0 , snake_case_ : Union[str, Any]=4_0_0 , snake_case_ : Optional[Any]=True , snake_case_ : Tuple=None , snake_case_ : List[Any]=True , snake_case_ : Tuple=[0.5, 0.5, 0.5] , snake_case_ : Optional[int]=[0.5, 0.5, 0.5] , snake_case_ : Dict=True , snake_case_ : Any=1 / 2_5_5 , snake_case_ : Any=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __a : List[Any] = parent __a : Optional[Any] = batch_size __a : int = num_channels __a : Any = min_resolution __a : Optional[Any] = max_resolution __a : List[str] = do_resize __a : Optional[int] = size __a : Dict = do_normalize __a : Any = image_mean __a : Tuple = image_std __a : Union[str, Any] = do_rescale __a : Union[str, Any] = rescale_factor __a : List[Any] = do_pad def lowerCAmelCase (self : str ): 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 lowerCAmelCase (self : Optional[int] , snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any]=False ): if not batched: __a : str = image_inputs[0] if isinstance(snake_case_ , Image.Image ): __a , __a : Tuple = image.size else: __a , __a : Tuple = image.shape[1], image.shape[2] if w < h: __a : int = int(self.size['''shortest_edge'''] * h / w ) __a : Any = self.size['''shortest_edge'''] elif w > h: __a : Tuple = self.size['''shortest_edge'''] __a : int = int(self.size['''shortest_edge'''] * w / h ) else: __a : List[Any] = self.size['''shortest_edge'''] __a : Dict = self.size['''shortest_edge'''] else: __a : Union[str, Any] = [] for image in image_inputs: __a , __a : List[str] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a : Union[str, Any] = max(snake_case_ , key=lambda snake_case_ : item[0] )[0] __a : Any = max(snake_case_ , key=lambda snake_case_ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCamelCase__ ( __lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = YolosImageProcessor if is_vision_available() else None def lowerCAmelCase (self : Any ): __a : Any = YolosImageProcessingTester(self ) @property def lowerCAmelCase (self : int ): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase (self : Optional[int] ): __a : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case_ , '''image_mean''' ) ) self.assertTrue(hasattr(snake_case_ , '''image_std''' ) ) self.assertTrue(hasattr(snake_case_ , '''do_normalize''' ) ) self.assertTrue(hasattr(snake_case_ , '''do_resize''' ) ) self.assertTrue(hasattr(snake_case_ , '''size''' ) ) def lowerCAmelCase (self : Union[str, Any] ): __a : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , snake_case_ ) __a : int = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=snake_case_ ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , snake_case_ ) def lowerCAmelCase (self : str ): pass def lowerCAmelCase (self : Optional[Any] ): # Initialize image_processing __a : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , Image.Image ) # Test not batched input __a : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a : int = self.image_processor_tester.get_expected_values(snake_case_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a : List[str] = self.image_processor_tester.get_expected_values(snake_case_ , batched=snake_case_ ) __a : str = image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase (self : str ): # Initialize image_processing __a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , numpify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , np.ndarray ) # Test not batched input __a : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a : Dict = self.image_processor_tester.get_expected_values(snake_case_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a : int = image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values __a , __a : List[str] = self.image_processor_tester.get_expected_values(snake_case_ , batched=snake_case_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase (self : Optional[Any] ): # Initialize image_processing __a : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , torchify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , torch.Tensor ) # Test not batched input __a : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __a , __a : Optional[Any] = self.image_processor_tester.get_expected_values(snake_case_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a : Tuple = image_processing(snake_case_ , return_tensors='''pt''' ).pixel_values __a , __a : Union[str, Any] = self.image_processor_tester.get_expected_values(snake_case_ , batched=snake_case_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase (self : Any ): # Initialize image_processings __a : Any = self.image_processing_class(**self.image_processor_dict ) __a : str = self.image_processing_class(do_resize=snake_case_ , do_normalize=snake_case_ , do_rescale=snake_case_ ) # create random PyTorch tensors __a : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , torchify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __a : List[Any] = image_processing_a.pad(snake_case_ , return_tensors='''pt''' ) __a : Union[str, Any] = image_processing_a(snake_case_ , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1E-4 ) ) @slow def lowerCAmelCase (self : List[str] ): # prepare image and target __a : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __a : str = json.loads(f.read() ) __a : Dict = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __a : Optional[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __a : Tuple = image_processing(images=snake_case_ , annotations=snake_case_ , return_tensors='''pt''' ) # verify pixel values __a : int = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , snake_case_ ) __a : Tuple = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , snake_case_ , atol=1E-4 ) ) # verify area __a : int = 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'''] , snake_case_ ) ) # verify boxes __a : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , snake_case_ ) __a : List[str] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , snake_case_ , atol=1E-3 ) ) # verify image_id __a : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , snake_case_ ) ) # verify is_crowd __a : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , snake_case_ ) ) # verify class_labels __a : Optional[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , snake_case_ ) ) # verify orig_size __a : Optional[int] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , snake_case_ ) ) # verify size __a : Optional[Any] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , snake_case_ ) ) @slow def lowerCAmelCase (self : Optional[int] ): # prepare image, target and masks_path __a : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __a : int = json.loads(f.read() ) __a : Optional[int] = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __a : List[str] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __a : Any = YolosImageProcessor(format='''coco_panoptic''' ) __a : Any = image_processing(images=snake_case_ , annotations=snake_case_ , masks_path=snake_case_ , return_tensors='''pt''' ) # verify pixel values __a : Tuple = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , snake_case_ ) __a : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , snake_case_ , atol=1E-4 ) ) # verify area __a : Optional[Any] = 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'''] , snake_case_ ) ) # verify boxes __a : int = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , snake_case_ ) __a : Tuple = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , snake_case_ , atol=1E-3 ) ) # verify image_id __a : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , snake_case_ ) ) # verify is_crowd __a : Any = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , snake_case_ ) ) # verify class_labels __a : Any = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , snake_case_ ) ) # verify masks __a : Tuple = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , snake_case_ ) # verify orig_size __a : Any = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , snake_case_ ) ) # verify size __a : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , snake_case_ ) )
326
from collections import deque class UpperCamelCase__ : def __init__(self : str , snake_case_ : str , snake_case_ : int , snake_case_ : int ): __a : Optional[Any] = process_name # process name __a : Optional[Any] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time __a : Union[str, Any] = arrival_time __a : int = burst_time # remaining burst time __a : Dict = 0 # total time of the process wait in ready queue __a : Union[str, Any] = 0 # time from arrival time to completion time class UpperCamelCase__ : def __init__(self : Optional[Any] , snake_case_ : int , snake_case_ : list[int] , snake_case_ : deque[Process] , snake_case_ : int , ): # total number of mlfq's queues __a : Tuple = number_of_queues # time slice of queues that round robin algorithm applied __a : Optional[int] = time_slices # unfinished process is in this ready_queue __a : Optional[int] = queue # current time __a : List[Any] = current_time # finished process is in this sequence queue __a : deque[Process] = deque() def lowerCAmelCase (self : Dict ): __a : Tuple = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def lowerCAmelCase (self : List[Any] , snake_case_ : list[Process] ): __a : Optional[int] = [] for i in range(len(snake_case_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def lowerCAmelCase (self : Optional[Any] , snake_case_ : list[Process] ): __a : Optional[int] = [] for i in range(len(snake_case_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def lowerCAmelCase (self : Optional[Any] , snake_case_ : list[Process] ): __a : Any = [] for i in range(len(snake_case_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def lowerCAmelCase (self : List[Any] , snake_case_ : deque[Process] ): return [q.burst_time for q in queue] def lowerCAmelCase (self : int , snake_case_ : Process ): process.waiting_time += self.current_time - process.stop_time return process.waiting_time def lowerCAmelCase (self : Tuple , snake_case_ : deque[Process] ): __a : deque[Process] = deque() # sequence deque of finished process while len(snake_case_ ) != 0: __a : Any = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(snake_case_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 __a : Dict = 0 # set the process's turnaround time because it is finished __a : Tuple = self.current_time - cp.arrival_time # set the completion time __a : Dict = self.current_time # add the process to queue that has finished queue finished.append(snake_case_ ) self.finish_queue.extend(snake_case_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def lowerCAmelCase (self : List[Any] , snake_case_ : deque[Process] , snake_case_ : int ): __a : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(snake_case_ ) ): __a : Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(snake_case_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time __a : Dict = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(snake_case_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished __a : Dict = 0 # set the finish time __a : Union[str, Any] = self.current_time # update the process' turnaround time because it is finished __a : List[Any] = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(snake_case_ ) self.finish_queue.extend(snake_case_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def lowerCAmelCase (self : Optional[Any] ): # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): __a , __a : str = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest lowercase__ =Process('P1', 0, 53) lowercase__ =Process('P2', 0, 17) lowercase__ =Process('P3', 0, 68) lowercase__ =Process('P4', 0, 24) lowercase__ =3 lowercase__ =[17, 25] lowercase__ =deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'queue': deque([Pa, Pa, Pa, Pa])}) lowercase__ =Process('P1', 0, 53) lowercase__ =Process('P2', 0, 17) lowercase__ =Process('P3', 0, 68) lowercase__ =Process('P4', 0, 24) lowercase__ =3 lowercase__ =[17, 25] lowercase__ =deque([Pa, Pa, Pa, Pa]) lowercase__ =MLFQ(number_of_queues, time_slices, queue, 0) lowercase__ =mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( F"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( F"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( F"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
326
1
"""simple docstring""" from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class UpperCamelCase__ ( _lowerCAmelCase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ) -> Any: A__ = path_or_paths A__ = split if split or isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else "train" A__ = features A__ = cache_dir A__ = keep_in_memory A__ = streaming A__ = num_proc A__ = kwargs @abstractmethod def snake_case__ ( self ) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: pass class UpperCamelCase__ ( _lowerCAmelCase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ) -> str: A__ = features A__ = cache_dir A__ = keep_in_memory A__ = streaming A__ = num_proc A__ = kwargs @abstractmethod def snake_case__ ( self ) -> Union[Dataset, IterableDataset]: pass
104
'''simple docstring''' import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __snake_case = 16 __snake_case = 32 def a ( __a , __a = 16 ) -> Dict: '''simple docstring''' UpperCamelCase__ :List[str] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) UpperCamelCase__ :Optional[Any] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase__ :Any = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase__ :str = datasets.map( __a , batched=__a , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase__ :Optional[int] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__a ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase__ :Union[str, Any] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase__ :str = 16 elif accelerator.mixed_precision != "no": UpperCamelCase__ :Tuple = 8 else: UpperCamelCase__ :int = None return tokenizer.pad( __a , padding='''longest''' , max_length=__a , pad_to_multiple_of=__a , return_tensors='''pt''' , ) # Instantiate dataloaders. UpperCamelCase__ :Any = DataLoader( tokenized_datasets['''train'''] , shuffle=__a , collate_fn=__a , batch_size=__a , drop_last=__a ) UpperCamelCase__ :Any = DataLoader( tokenized_datasets['''validation'''] , shuffle=__a , collate_fn=__a , batch_size=__a , drop_last=(accelerator.mixed_precision == '''fp8''') , ) return train_dataloader, eval_dataloader def a ( __a , __a ) -> Dict: '''simple docstring''' UpperCamelCase__ :List[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase__ :List[Any] = config['''lr'''] UpperCamelCase__ :List[str] = int(config['''num_epochs'''] ) UpperCamelCase__ :int = int(config['''seed'''] ) UpperCamelCase__ :str = int(config['''batch_size'''] ) UpperCamelCase__ :List[str] = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation UpperCamelCase__ :Tuple = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: UpperCamelCase__ :Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE UpperCamelCase__ :Dict = MAX_GPU_BATCH_SIZE set_seed(__a ) UpperCamelCase__ , UpperCamelCase__ :Tuple = get_dataloaders(__a , __a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase__ :List[Any] = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase__ :Optional[int] = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase__ :Union[str, Any] = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler UpperCamelCase__ :Optional[Any] = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=100 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :str = accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) UpperCamelCase__ :Dict = model(**__a ) UpperCamelCase__ :Union[str, Any] = outputs.loss UpperCamelCase__ :Tuple = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase__ :Optional[int] = model(**__a ) UpperCamelCase__ :int = outputs.logits.argmax(dim=-1 ) UpperCamelCase__ , UpperCamelCase__ :List[Any] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__a , references=__a , ) UpperCamelCase__ :List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , __a ) def a ( ) -> List[Any]: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=__a , default=__a , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) UpperCamelCase__ :int = parser.parse_args() UpperCamelCase__ :int = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__a , __a ) if __name__ == "__main__": main()
189
0
'''simple docstring''' import string def lowerCamelCase ( lowerCamelCase : str): A_ : List[str] = """""" for i in sequence: A_ : Dict = ord(lowerCamelCase) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def lowerCamelCase ( lowerCamelCase : str): A_ : Union[str, Any] = string.ascii_letters A_ : int = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowerCamelCase)] if c in letters else c for c in sequence) def lowerCamelCase ( ): from timeit import timeit print("""Running performance benchmarks...""") A_ : Optional[int] = """from string import printable ; from __main__ import atbash, atbash_slow""" print(F'> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowerCamelCase)} seconds') print(F'> atbash(): {timeit("atbash(printable)" , setup=lowerCamelCase)} seconds') if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
704
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['NllbTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['NllbTokenizerFast'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
'''simple docstring''' import os from pathlib import Path def A__ ( ): from torch.utils.cpp_extension import load _UpperCamelCase : Optional[Any] = Path(UpperCAmelCase_ ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' _UpperCamelCase : Tuple = [ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' , 'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' , 'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' , UpperCAmelCase_ , with_cuda=UpperCAmelCase_ , extra_include_paths=[str(UpperCAmelCase_ )] , extra_cflags=['-DWITH_CUDA=1'] , extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
195
'''simple docstring''' import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(lowerCamelCase__ ): _UpperCamelCase : Optional[int] = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) _UpperCamelCase : Dict = FlaxAutoModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: with self.subTest(lowerCamelCase__ ): _UpperCamelCase : Any = AutoConfig.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) _UpperCamelCase : Any = FlaxAutoModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) self.assertIsInstance(lowerCamelCase__ ,lowerCamelCase__ ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: _UpperCamelCase : Optional[int] = AutoTokenizer.from_pretrained(lowerCamelCase__ ) _UpperCamelCase : List[Any] = FlaxBertModel.from_pretrained(lowerCamelCase__ ) _UpperCamelCase : Optional[int] = tokenizer('Do you support jax jitted function?' ,return_tensors=TensorType.JAX ) @jax.jit def eval(**lowerCamelCase__ : Union[str, Any] ): return model(**lowerCamelCase__ ) eval(**lowerCamelCase__ ).block_until_ready() @slow def UpperCamelCase_ ( self : Dict ): '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: _UpperCamelCase : Optional[int] = AutoTokenizer.from_pretrained(lowerCamelCase__ ) _UpperCamelCase : Tuple = FlaxRobertaModel.from_pretrained(lowerCamelCase__ ) _UpperCamelCase : Optional[Any] = tokenizer('Do you support jax jitted function?' ,return_tensors=TensorType.JAX ) @jax.jit def eval(**lowerCamelCase__ : Union[str, Any] ): return model(**lowerCamelCase__ ) eval(**lowerCamelCase__ ).block_until_ready() def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,'bert-base is not a local folder and is not a valid model identifier' ): _UpperCamelCase : int = FlaxAutoModel.from_pretrained('bert-base' ) def UpperCamelCase_ ( self : str ): '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): _UpperCamelCase : Tuple = FlaxAutoModel.from_pretrained(lowerCamelCase__ ,revision='aaaaaa' ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' with self.assertRaisesRegex( lowerCamelCase__ ,'hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack' ,): _UpperCamelCase : List[Any] = FlaxAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' with self.assertRaisesRegex(lowerCamelCase__ ,'Use `from_pt=True` to load this model' ): _UpperCamelCase : Tuple = FlaxAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
195
1
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 : List[Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:int = ["pixel_values"] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , )-> None: super().__init__(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =size if size is not None else {"""shortest_edge""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCamelCase_ =image_std if image_std is not None else OPENAI_CLIP_STD lowerCamelCase_ =do_convert_rgb def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) lowerCamelCase_ =get_resize_output_image_size(_SCREAMING_SNAKE_CASE , size=size["""shortest_edge"""] , default_to_square=_SCREAMING_SNAKE_CASE ) return resize(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE ) 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(_SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> Tuple: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , )-> PIL.Image.Image: lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""size""" , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(_SCREAMING_SNAKE_CASE , param_name="""crop_size""" , default_to_square=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =image_mean if image_mean is not None else self.image_mean lowerCamelCase_ =image_std if image_std is not None else self.image_std lowerCamelCase_ =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCamelCase_ =make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: 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: lowerCamelCase_ =[convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(image=_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] lowerCamelCase_ ={"""pixel_values""": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
75
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
1
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase__ : '''simple docstring''' def __init__( self, __magic_name__, __magic_name__=12, __magic_name__=7, __magic_name__=True, __magic_name__=True, __magic_name__=True, __magic_name__=99, __magic_name__=32, __magic_name__=32, __magic_name__=2, __magic_name__=4, __magic_name__=37, __magic_name__=0.1, __magic_name__=0.1, __magic_name__=512, __magic_name__=0.02, __magic_name__=0, __magic_name__=None, ) -> Dict: """simple docstring""" UpperCamelCase__ : Union[str, Any] = parent UpperCamelCase__ : Any = batch_size UpperCamelCase__ : List[str] = seq_length UpperCamelCase__ : List[Any] = is_training UpperCamelCase__ : Union[str, Any] = use_input_mask UpperCamelCase__ : Tuple = use_labels UpperCamelCase__ : Optional[Any] = vocab_size UpperCamelCase__ : Dict = hidden_size UpperCamelCase__ : Any = projection_dim UpperCamelCase__ : str = num_hidden_layers UpperCamelCase__ : List[str] = num_attention_heads UpperCamelCase__ : List[str] = intermediate_size UpperCamelCase__ : str = dropout UpperCamelCase__ : Union[str, Any] = attention_dropout UpperCamelCase__ : str = max_position_embeddings UpperCamelCase__ : Tuple = initializer_range UpperCamelCase__ : Dict = scope UpperCamelCase__ : str = bos_token_id def UpperCamelCase__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : List[str] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) UpperCamelCase__ : Tuple = None if self.use_input_mask: UpperCamelCase__ : int = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: UpperCamelCase__ : List[str] = input_mask.numpy() UpperCamelCase__ ,UpperCamelCase__ : Union[str, Any] = input_mask.shape UpperCamelCase__ : Tuple = np.random.randint(1, seq_length - 1, size=(batch_size,) ) for batch_idx, start_index in enumerate(__magic_name__ ): UpperCamelCase__ : Tuple = 1 UpperCamelCase__ : Optional[int] = 0 UpperCamelCase__ : Dict = self.get_config() return config, input_ids, tf.convert_to_tensor(__magic_name__ ) def UpperCamelCase__ ( self ) -> Optional[Any]: """simple docstring""" return BlipTextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, projection_dim=self.projection_dim, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, bos_token_id=self.bos_token_id, ) def UpperCamelCase__ ( self, __magic_name__, __magic_name__, __magic_name__ ) -> Tuple: """simple docstring""" UpperCamelCase__ : Any = TFBlipTextModel(config=__magic_name__ ) UpperCamelCase__ : Dict = model(__magic_name__, attention_mask=__magic_name__, training=__magic_name__ ) UpperCamelCase__ : List[str] = model(__magic_name__, training=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size) ) def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase__ : str = self.prepare_config_and_inputs() UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ : str = config_and_inputs UpperCamelCase__ : int = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowercase__ ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' a : int = (TFBlipTextModel,) if is_tf_available() else () a : List[Any] = False a : Union[str, Any] = False a : List[Any] = False def UpperCamelCase__ ( self ) -> str: """simple docstring""" UpperCamelCase__ : Union[str, Any] = BlipTextModelTester(self ) UpperCamelCase__ : List[Any] = ConfigTester(self, config_class=__magic_name__, hidden_size=37 ) def UpperCamelCase__ ( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" pass def UpperCamelCase__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason='''Blip does not use inputs_embeds''' ) def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @slow def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ : int = TFBlipTextModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def UpperCamelCase__ ( self, __magic_name__=True ) -> List[str]: """simple docstring""" super().test_pt_tf_model_equivalence(allow_missing_keys=__magic_name__ )
253
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class lowercase__ ( __lowerCamelCase ): '''simple docstring''' a : Union[List[PIL.Image.Image], np.ndarray] a : Optional[List[bool]] a : 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_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
253
1
from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP _lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name _lowercase = ''' Examples: ```py >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline >>> import torch >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior") >>> pipe_prior.to("cuda") >>> prompt = "red cat, 4k photo" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> negative_image_emb = out.negative_image_embeds >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1") >>> pipe.to("cuda") >>> image = pipe( ... prompt, ... image_embeds=image_emb, ... negative_image_embeds=negative_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... ).images >>> image[0].save("cat.png") ``` ''' def _A (UpperCamelCase : List[Any] , UpperCamelCase : Dict , UpperCamelCase : Any=8 ) ->List[str]: '''simple docstring''' lowerCamelCase__ : Optional[Any] = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 lowerCamelCase__ : Union[str, Any] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class __A ( A_ ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , ): super().__init__() self.register_modules( text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , movq=__magic_name__ , ) lowerCamelCase__ : int = 2 ** (len(self.movq.config.block_out_channels ) - 1) def _snake_case (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): if latents is None: lowerCamelCase__ : Tuple = randn_tensor(__magic_name__ , generator=__magic_name__ , device=__magic_name__ , dtype=__magic_name__ ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) lowerCamelCase__ : Dict = latents.to(__magic_name__ ) lowerCamelCase__ : Optional[Any] = latents * scheduler.init_noise_sigma return latents def _snake_case (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , ): lowerCamelCase__ : Optional[Any] = len(__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else 1 # get prompt text embeddings lowerCamelCase__ : Optional[Any] = self.tokenizer( __magic_name__ , padding="""max_length""" , truncation=__magic_name__ , max_length=77 , return_attention_mask=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors="""pt""" , ) lowerCamelCase__ : Any = text_inputs.input_ids lowerCamelCase__ : Optional[Any] = self.tokenizer(__magic_name__ , padding="""longest""" , return_tensors="""pt""" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__magic_name__ , __magic_name__ ): lowerCamelCase__ : Union[str, Any] = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) lowerCamelCase__ : List[str] = text_input_ids.to(__magic_name__ ) lowerCamelCase__ : Tuple = text_inputs.attention_mask.to(__magic_name__ ) lowerCamelCase__ ,lowerCamelCase__ : str = self.text_encoder( input_ids=__magic_name__ , attention_mask=__magic_name__ ) lowerCamelCase__ : int = prompt_embeds.repeat_interleave(__magic_name__ , dim=0 ) lowerCamelCase__ : Dict = text_encoder_hidden_states.repeat_interleave(__magic_name__ , dim=0 ) lowerCamelCase__ : Any = text_mask.repeat_interleave(__magic_name__ , dim=0 ) if do_classifier_free_guidance: lowerCamelCase__ : List[str] if negative_prompt is None: lowerCamelCase__ : Any = [""""""] * batch_size elif type(__magic_name__ ) is not type(__magic_name__ ): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(__magic_name__ )} !=" f" {type(__magic_name__ )}." ) elif isinstance(__magic_name__ , __magic_name__ ): lowerCamelCase__ : Optional[Any] = [negative_prompt] elif batch_size != len(__magic_name__ ): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(__magic_name__ )}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: lowerCamelCase__ : Any = negative_prompt lowerCamelCase__ : Dict = self.tokenizer( __magic_name__ , padding="""max_length""" , max_length=77 , truncation=__magic_name__ , return_attention_mask=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors="""pt""" , ) lowerCamelCase__ : Optional[Any] = uncond_input.input_ids.to(__magic_name__ ) lowerCamelCase__ : Optional[int] = uncond_input.attention_mask.to(__magic_name__ ) lowerCamelCase__ ,lowerCamelCase__ : Dict = self.text_encoder( input_ids=__magic_name__ , attention_mask=__magic_name__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase__ : str = negative_prompt_embeds.shape[1] lowerCamelCase__ : Union[str, Any] = negative_prompt_embeds.repeat(1 , __magic_name__ ) lowerCamelCase__ : Any = negative_prompt_embeds.view(batch_size * num_images_per_prompt , __magic_name__ ) lowerCamelCase__ : Optional[int] = uncond_text_encoder_hidden_states.shape[1] lowerCamelCase__ : Optional[int] = uncond_text_encoder_hidden_states.repeat(1 , __magic_name__ , 1 ) lowerCamelCase__ : Optional[int] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , __magic_name__ , -1 ) lowerCamelCase__ : Optional[int] = uncond_text_mask.repeat_interleave(__magic_name__ , dim=0 ) # done duplicates # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase__ : List[Any] = torch.cat([negative_prompt_embeds, prompt_embeds] ) lowerCamelCase__ : List[str] = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) lowerCamelCase__ : List[str] = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def _snake_case (self , __magic_name__=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) lowerCamelCase__ : Optional[Any] = torch.device(f"cuda:{gpu_id}" ) lowerCamelCase__ : int = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__magic_name__ , __magic_name__ ) def _snake_case (self , __magic_name__=0 ): if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) lowerCamelCase__ : int = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=__magic_name__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) lowerCamelCase__ : Tuple = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: lowerCamelCase__ ,lowerCamelCase__ : Any = cpu_offload_with_hook(__magic_name__ , __magic_name__ , prev_module_hook=__magic_name__ ) if self.safety_checker is not None: lowerCamelCase__ ,lowerCamelCase__ : Optional[int] = cpu_offload_with_hook(self.safety_checker , __magic_name__ , prev_module_hook=__magic_name__ ) # We'll offload the last model manually. lowerCamelCase__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _snake_case (self ): if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(__magic_name__ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__magic_name__ ) def __call__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__ = 512 , __magic_name__ = 512 , __magic_name__ = 100 , __magic_name__ = 4.0 , __magic_name__ = 1 , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "pil" , __magic_name__ = True , ): if isinstance(__magic_name__ , __magic_name__ ): lowerCamelCase__ : int = 1 elif isinstance(__magic_name__ , __magic_name__ ): lowerCamelCase__ : Optional[int] = len(__magic_name__ ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(__magic_name__ )}" ) lowerCamelCase__ : str = self._execution_device lowerCamelCase__ : Optional[int] = batch_size * num_images_per_prompt lowerCamelCase__ : Union[str, Any] = guidance_scale > 1.0 lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ : Union[str, Any] = self._encode_prompt( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ): lowerCamelCase__ : Tuple = torch.cat(__magic_name__ , dim=0 ) if isinstance(__magic_name__ , __magic_name__ ): lowerCamelCase__ : Any = torch.cat(__magic_name__ , dim=0 ) if do_classifier_free_guidance: lowerCamelCase__ : Union[str, Any] = image_embeds.repeat_interleave(__magic_name__ , dim=0 ) lowerCamelCase__ : Optional[Any] = negative_image_embeds.repeat_interleave(__magic_name__ , dim=0 ) lowerCamelCase__ : Dict = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=__magic_name__ ) self.scheduler.set_timesteps(__magic_name__ , device=__magic_name__ ) lowerCamelCase__ : Dict = self.scheduler.timesteps lowerCamelCase__ : Union[str, Any] = self.unet.config.in_channels lowerCamelCase__ ,lowerCamelCase__ : Union[str, Any] = get_new_h_w(__magic_name__ , __magic_name__ , self.movq_scale_factor ) # create initial latent lowerCamelCase__ : Tuple = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , __magic_name__ , __magic_name__ , __magic_name__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(__magic_name__ ) ): # expand the latents if we are doing classifier free guidance lowerCamelCase__ : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowerCamelCase__ : Union[str, Any] = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} lowerCamelCase__ : Union[str, Any] = self.unet( sample=__magic_name__ , timestep=__magic_name__ , encoder_hidden_states=__magic_name__ , added_cond_kwargs=__magic_name__ , return_dict=__magic_name__ , )[0] if do_classifier_free_guidance: lowerCamelCase__ ,lowerCamelCase__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) lowerCamelCase__ ,lowerCamelCase__ : str = noise_pred.chunk(2 ) lowerCamelCase__ ,lowerCamelCase__ : Union[str, Any] = variance_pred.chunk(2 ) lowerCamelCase__ : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) lowerCamelCase__ : int = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): lowerCamelCase__ ,lowerCamelCase__ : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase__ : Dict = self.scheduler.step( __magic_name__ , __magic_name__ , __magic_name__ , generator=__magic_name__ , ).prev_sample # post-processing lowerCamelCase__ : List[str] = self.movq.decode(__magic_name__ , force_not_quantize=__magic_name__ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: lowerCamelCase__ : Optional[int] = image * 0.5 + 0.5 lowerCamelCase__ : Any = image.clamp(0 , 1 ) lowerCamelCase__ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": lowerCamelCase__ : Any = self.numpy_to_pil(__magic_name__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=__magic_name__ )
96
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _lowercase = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class __A ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=None , __magic_name__=True , __magic_name__=True , __magic_name__=None , ): lowerCamelCase__ : Optional[Any] = size if size is not None else {"""height""": 20, """width""": 20} lowerCamelCase__ : List[str] = parent lowerCamelCase__ : str = batch_size lowerCamelCase__ : List[str] = num_channels lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Union[str, Any] = min_resolution lowerCamelCase__ : List[Any] = max_resolution lowerCamelCase__ : Optional[int] = size lowerCamelCase__ : List[str] = do_normalize lowerCamelCase__ : str = do_convert_rgb lowerCamelCase__ : str = [512, 1024, 2048, 4096] lowerCamelCase__ : Any = patch_size if patch_size is not None else {"""height""": 16, """width""": 16} def _snake_case (self ): return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def _snake_case (self ): lowerCamelCase__ : List[str] = """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg""" lowerCamelCase__ : int = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ).convert("""RGB""" ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class __A ( A_ , unittest.TestCase ): UpperCamelCase :Union[str, Any] = PixaStructImageProcessor if is_vision_available() else None def _snake_case (self ): lowerCamelCase__ : List[str] = PixaStructImageProcessingTester(self ) @property def _snake_case (self ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case (self ): lowerCamelCase__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , """do_normalize""" ) ) self.assertTrue(hasattr(__magic_name__ , """do_convert_rgb""" ) ) def _snake_case (self ): lowerCamelCase__ : Tuple = self.image_processor_tester.prepare_dummy_image() lowerCamelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) lowerCamelCase__ : List[str] = 2048 lowerCamelCase__ : Any = image_processor(__magic_name__ , return_tensors="""pt""" , max_patches=__magic_name__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06 ) , atol=1E-3 , rtol=1E-3 ) ) def _snake_case (self ): # Initialize image_processor lowerCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input lowerCamelCase__ : Optional[Any] = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input lowerCamelCase__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched lowerCamelCase__ : Optional[Any] = image_processor( __magic_name__ , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _snake_case (self ): # Initialize image_processor lowerCamelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input lowerCamelCase__ : List[Any] = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 lowerCamelCase__ : List[str] = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(__magic_name__ ): lowerCamelCase__ : Tuple = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches lowerCamelCase__ : Optional[Any] = """Hello""" lowerCamelCase__ : Dict = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__magic_name__ , header_text=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched lowerCamelCase__ : Tuple = image_processor( __magic_name__ , return_tensors="""pt""" , max_patches=__magic_name__ , header_text=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _snake_case (self ): # Initialize image_processor lowerCamelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) lowerCamelCase__ : Optional[int] = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input lowerCamelCase__ : List[str] = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched lowerCamelCase__ : List[str] = image_processor( __magic_name__ , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _snake_case (self ): # Initialize image_processor lowerCamelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input lowerCamelCase__ : List[str] = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input lowerCamelCase__ : Tuple = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched lowerCamelCase__ : Optional[Any] = image_processor( __magic_name__ , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class __A ( A_ , unittest.TestCase ): UpperCamelCase :Optional[int] = PixaStructImageProcessor if is_vision_available() else None def _snake_case (self ): lowerCamelCase__ : Optional[Any] = PixaStructImageProcessingTester(self , num_channels=4 ) lowerCamelCase__ : Optional[int] = 3 @property def _snake_case (self ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case (self ): lowerCamelCase__ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , """do_normalize""" ) ) self.assertTrue(hasattr(__magic_name__ , """do_convert_rgb""" ) ) def _snake_case (self ): # Initialize image_processor lowerCamelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input lowerCamelCase__ : List[str] = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input lowerCamelCase__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched lowerCamelCase__ : str = image_processor( __magic_name__ , return_tensors="""pt""" , max_patches=__magic_name__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
96
1
'''simple docstring''' from collections import Counter from timeit import timeit def _lowerCAmelCase ( lowercase = "" , ) -> bool: return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def _lowerCAmelCase ( lowercase = "" ) -> bool: if len(lowercase ) == 0: return True __lowerCAmelCase = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string __lowerCAmelCase = {} for character in lower_case_input_str: __lowerCAmelCase = character_freq_dict.get(lowercase , 0 ) + 1 __lowerCAmelCase = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def _lowerCAmelCase ( lowercase = "" ) -> None: print("""\nFor string = """ , lowercase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(lowercase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(lowercase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": _a : int = input( """Enter string to determine if it can be rearranged as a palindrome or not: """ ).strip() benchmark(check_str) _a : Optional[int] = can_string_be_rearranged_as_palindrome_counter(check_str) print(f'{check_str} can {"" if status else "not "}be rearranged as a palindrome')
689
'''simple docstring''' import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def _lowerCAmelCase ( lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: # load base model __lowerCAmelCase = StableDiffusionPipeline.from_pretrained(lowercase , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors __lowerCAmelCase = load_file(lowercase ) __lowerCAmelCase = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: __lowerCAmelCase = key.split(""".""" )[0].split(LORA_PREFIX_TEXT_ENCODER + """_""" )[-1].split("""_""" ) __lowerCAmelCase = pipeline.text_encoder else: __lowerCAmelCase = key.split(""".""" )[0].split(LORA_PREFIX_UNET + """_""" )[-1].split("""_""" ) __lowerCAmelCase = pipeline.unet # find the target layer __lowerCAmelCase = layer_infos.pop(0 ) while len(lowercase ) > -1: try: __lowerCAmelCase = curr_layer.__getattr__(lowercase ) if len(lowercase ) > 0: __lowerCAmelCase = layer_infos.pop(0 ) elif len(lowercase ) == 0: break except Exception: if len(lowercase ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: __lowerCAmelCase = layer_infos.pop(0 ) __lowerCAmelCase = [] if "lora_down" in key: pair_keys.append(key.replace("""lora_down""" , """lora_up""" ) ) pair_keys.append(lowercase ) else: pair_keys.append(lowercase ) pair_keys.append(key.replace("""lora_up""" , """lora_down""" ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: __lowerCAmelCase = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) __lowerCAmelCase = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase , lowercase ).unsqueeze(2 ).unsqueeze(3 ) else: __lowerCAmelCase = state_dict[pair_keys[0]].to(torch.floataa ) __lowerCAmelCase = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase , lowercase ) # update visited list for item in pair_keys: visited.append(lowercase ) return pipeline if __name__ == "__main__": _a : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( """--base_model_path""", default=None, type=str, required=True, help="""Path to the base model in diffusers format.""" ) parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument( """--lora_prefix_unet""", default="""lora_unet""", type=str, help="""The prefix of UNet weight in safetensors""" ) parser.add_argument( """--lora_prefix_text_encoder""", default="""lora_te""", type=str, help="""The prefix of text encoder weight in safetensors""", ) parser.add_argument("""--alpha""", default=0.75, type=float, help="""The merging ratio in W = W0 + alpha * deltaW""") parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""" ) parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") _a : Optional[int] = parser.parse_args() _a : Dict = args.base_model_path _a : Optional[Any] = args.checkpoint_path _a : Union[str, Any] = args.dump_path _a : Optional[int] = args.lora_prefix_unet _a : int = args.lora_prefix_text_encoder _a : str = args.alpha _a : Any = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) _a : Tuple = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
689
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCamelCase__ : List[str] = logging.get_logger(__name__) class _UpperCamelCase ( lowerCamelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowerCAmelCase__ : str , **lowerCAmelCase__ : Any ): """simple docstring""" warnings.warn( """The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DeiTImageProcessor instead.""" , lowerCAmelCase__ , ) super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ )
178
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def lowerCAmelCase_ ( _lowerCamelCase: Tuple ): __SCREAMING_SNAKE_CASE : List[Any] = SwinvaConfig() __SCREAMING_SNAKE_CASE : List[Any] = swinva_name.split("""_""" ) __SCREAMING_SNAKE_CASE : Union[str, Any] = name_split[1] if "to" in name_split[3]: __SCREAMING_SNAKE_CASE : Dict = int(name_split[3][-3:] ) else: __SCREAMING_SNAKE_CASE : str = int(name_split[3] ) if "to" in name_split[2]: __SCREAMING_SNAKE_CASE : Optional[Any] = int(name_split[2][-2:] ) else: __SCREAMING_SNAKE_CASE : Optional[int] = int(name_split[2][6:] ) if model_size == "tiny": __SCREAMING_SNAKE_CASE : Dict = 96 __SCREAMING_SNAKE_CASE : List[str] = (2, 2, 6, 2) __SCREAMING_SNAKE_CASE : List[Any] = (3, 6, 12, 24) elif model_size == "small": __SCREAMING_SNAKE_CASE : List[str] = 96 __SCREAMING_SNAKE_CASE : int = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE : int = (3, 6, 12, 24) elif model_size == "base": __SCREAMING_SNAKE_CASE : int = 1_28 __SCREAMING_SNAKE_CASE : str = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE : Optional[int] = (4, 8, 16, 32) else: __SCREAMING_SNAKE_CASE : List[str] = 1_92 __SCREAMING_SNAKE_CASE : Union[str, Any] = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE : Dict = (6, 12, 24, 48) if "to" in swinva_name: __SCREAMING_SNAKE_CASE : int = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): __SCREAMING_SNAKE_CASE : int = 2_18_41 __SCREAMING_SNAKE_CASE : str = """huggingface/label-files""" __SCREAMING_SNAKE_CASE : List[str] = """imagenet-22k-id2label.json""" __SCREAMING_SNAKE_CASE : List[str] = json.load(open(hf_hub_download(_lowerCamelCase , _lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) __SCREAMING_SNAKE_CASE : List[Any] = {int(_lowerCamelCase ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : Optional[int] = idalabel __SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} else: __SCREAMING_SNAKE_CASE : str = 10_00 __SCREAMING_SNAKE_CASE : Optional[int] = """huggingface/label-files""" __SCREAMING_SNAKE_CASE : Any = """imagenet-1k-id2label.json""" __SCREAMING_SNAKE_CASE : Optional[int] = json.load(open(hf_hub_download(_lowerCamelCase , _lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) __SCREAMING_SNAKE_CASE : int = {int(_lowerCamelCase ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : Optional[int] = idalabel __SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE : Any = img_size __SCREAMING_SNAKE_CASE : Union[str, Any] = num_classes __SCREAMING_SNAKE_CASE : int = embed_dim __SCREAMING_SNAKE_CASE : Dict = depths __SCREAMING_SNAKE_CASE : str = num_heads __SCREAMING_SNAKE_CASE : int = window_size return config def lowerCAmelCase_ ( _lowerCamelCase: int ): if "patch_embed.proj" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: __SCREAMING_SNAKE_CASE : Optional[int] = """encoder.""" + name if "attn.proj" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __SCREAMING_SNAKE_CASE : Any = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __SCREAMING_SNAKE_CASE : List[Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if "q_bias" in name: __SCREAMING_SNAKE_CASE : Tuple = name.replace("""q_bias""" , """query.bias""" ) if "k_bias" in name: __SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""k_bias""" , """key.bias""" ) if "v_bias" in name: __SCREAMING_SNAKE_CASE : List[str] = name.replace("""v_bias""" , """value.bias""" ) if "cpb_mlp" in name: __SCREAMING_SNAKE_CASE : str = name.replace("""cpb_mlp""" , """continuous_position_bias_mlp""" ) if name == "norm.weight": __SCREAMING_SNAKE_CASE : Tuple = """layernorm.weight""" if name == "norm.bias": __SCREAMING_SNAKE_CASE : Optional[int] = """layernorm.bias""" if "head" in name: __SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("""head""" , """classifier""" ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = """swinv2.""" + name return name def lowerCAmelCase_ ( _lowerCamelCase: int , _lowerCamelCase: Optional[Any] ): for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE : Optional[Any] = orig_state_dict.pop(_lowerCamelCase ) if "mask" in key: continue elif "qkv" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = key.split(""".""" ) __SCREAMING_SNAKE_CASE : List[str] = int(key_split[1] ) __SCREAMING_SNAKE_CASE : Dict = int(key_split[3] ) __SCREAMING_SNAKE_CASE : str = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] __SCREAMING_SNAKE_CASE : str = val[dim : dim * 2, :] __SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: __SCREAMING_SNAKE_CASE : Optional[Any] = val[:dim] __SCREAMING_SNAKE_CASE : int = val[ dim : dim * 2 ] __SCREAMING_SNAKE_CASE : int = val[-dim:] else: __SCREAMING_SNAKE_CASE : Optional[Any] = val return orig_state_dict def lowerCAmelCase_ ( _lowerCamelCase: Tuple , _lowerCamelCase: int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = timm.create_model(_lowerCamelCase , pretrained=_lowerCamelCase ) timm_model.eval() __SCREAMING_SNAKE_CASE : int = get_swinva_config(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = SwinvaForImageClassification(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Optional[int] = convert_state_dict(timm_model.state_dict() , _lowerCamelCase ) model.load_state_dict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" __SCREAMING_SNAKE_CASE : List[Any] = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swinva_name.replace("""_""" , """-""" ) ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=_lowerCamelCase , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE : int = timm_model(inputs["""pixel_values"""] ) __SCREAMING_SNAKE_CASE : Dict = model(**_lowerCamelCase ).logits assert torch.allclose(_lowerCamelCase , _lowerCamelCase , atol=1E-3 ) print(F"Saving model {swinva_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCamelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_lowerCamelCase ) model.push_to_hub( repo_path_or_name=Path(_lowerCamelCase , _lowerCamelCase ) , organization="""nandwalritik""" , commit_message="""Add model""" , ) if __name__ == "__main__": UpperCamelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) UpperCamelCase__ : Optional[int] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
178
1
"""simple docstring""" import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow lowercase_ = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ "text-classification", "language-modeling", "summarization", "token-classification", "question-answering", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) lowercase_ = logging.getLogger() def A_ ( ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = argparse.ArgumentParser() parser.add_argument("""-f""" ) UpperCAmelCase_ : int = parser.parse_args() return args.f def A_ ( lowercase , lowercase="eval" ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Any = os.path.join(lowercase , f'''{split}_results.json''' ) if os.path.exists(lowercase ): with open(lowercase , """r""" ) as f: return json.load(lowercase ) raise ValueError(f'''can\'t find {path}''' ) lowercase_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" def a ( self : str )-> int: """simple docstring""" UpperCAmelCase_ : Tuple = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : Any = f''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(a_ , """argv""" , a_ ): run_flax_glue.main() UpperCAmelCase_ : List[str] = get_results(a_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) @slow def a ( self : List[str] )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : Tuple = f''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(a_ , """argv""" , a_ ): run_clm_flax.main() UpperCAmelCase_ : int = get_results(a_ ) self.assertLess(result["""eval_perplexity"""] , 1_00 ) @slow def a ( self : List[str] )-> Dict: """simple docstring""" UpperCAmelCase_ : int = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : List[str] = f''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(a_ , """argv""" , a_ ): run_summarization_flax.main() UpperCAmelCase_ : List[str] = get_results(a_ , split="""test""" ) self.assertGreaterEqual(result["""test_rouge1"""] , 10 ) self.assertGreaterEqual(result["""test_rouge2"""] , 2 ) self.assertGreaterEqual(result["""test_rougeL"""] , 7 ) self.assertGreaterEqual(result["""test_rougeLsum"""] , 7 ) @slow def a ( self : List[Any] )-> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : Optional[Any] = f''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(a_ , """argv""" , a_ ): run_mlm_flax.main() UpperCAmelCase_ : Tuple = get_results(a_ ) self.assertLess(result["""eval_perplexity"""] , 42 ) @slow def a ( self : str )-> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : Dict = f''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(a_ , """argv""" , a_ ): run_ta_mlm_flax.main() UpperCAmelCase_ : Tuple = get_results(a_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.42 ) @slow def a ( self : Union[str, Any] )-> List[str]: """simple docstring""" UpperCAmelCase_ : List[str] = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ : List[Any] = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : Optional[int] = f''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(a_ , """argv""" , a_ ): run_flax_ner.main() UpperCAmelCase_ : Optional[Any] = get_results(a_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertGreaterEqual(result["""eval_f1"""] , 0.3 ) @slow def a ( self : Optional[Any] )-> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.get_auto_remove_tmp_dir() UpperCAmelCase_ : Any = f''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(a_ , """argv""" , a_ ): run_qa.main() UpperCAmelCase_ : Tuple = get_results(a_ ) self.assertGreaterEqual(result["""eval_f1"""] , 30 ) self.assertGreaterEqual(result["""eval_exact"""] , 30 )
470
"""simple docstring""" import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="""session""" ) def A_ ( ) -> str: """simple docstring""" UpperCAmelCase_ : int = 10 UpperCAmelCase_ : Optional[Any] = datasets.Features( { """tokens""": datasets.Sequence(datasets.Value("""string""" ) ), """labels""": datasets.Sequence(datasets.ClassLabel(names=["""negative""", """positive"""] ) ), """answers""": datasets.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), """id""": datasets.Value("""int64""" ), } ) UpperCAmelCase_ : List[Any] = datasets.Dataset.from_dict( { """tokens""": [["""foo"""] * 5] * n, """labels""": [[1] * 5] * n, """answers""": [{"""answer_start""": [97], """text""": ["""1976"""]}] * 10, """id""": list(range(lowercase ) ), } , features=lowercase , ) return dataset @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[Any] = str(tmp_path_factory.mktemp("""data""" ) / """file.arrow""" ) dataset.map(cache_file_name=lowercase ) return filename # FILE_CONTENT + files lowercase_ = "\\n Text data.\n Second line of data." @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : int = tmp_path_factory.mktemp("""data""" ) / """file.txt""" UpperCAmelCase_ : Tuple = FILE_CONTENT with open(lowercase , """w""" ) as f: f.write(lowercase ) return filename @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Dict: """simple docstring""" import bza UpperCAmelCase_ : int = tmp_path_factory.mktemp("""data""" ) / """file.txt.bz2""" UpperCAmelCase_ : List[str] = bytes(lowercase , """utf-8""" ) with bza.open(lowercase , """wb""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> List[str]: """simple docstring""" import gzip UpperCAmelCase_ : List[str] = str(tmp_path_factory.mktemp("""data""" ) / """file.txt.gz""" ) UpperCAmelCase_ : Optional[Any] = bytes(lowercase , """utf-8""" ) with gzip.open(lowercase , """wb""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Union[str, Any]: """simple docstring""" if datasets.config.LZ4_AVAILABLE: import lza.frame UpperCAmelCase_ : Dict = tmp_path_factory.mktemp("""data""" ) / """file.txt.lz4""" UpperCAmelCase_ : str = bytes(lowercase , """utf-8""" ) with lza.frame.open(lowercase , """wb""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> Optional[Any]: """simple docstring""" if datasets.config.PY7ZR_AVAILABLE: import pyazr UpperCAmelCase_ : List[str] = tmp_path_factory.mktemp("""data""" ) / """file.txt.7z""" with pyazr.SevenZipFile(lowercase , """w""" ) as archive: archive.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> Union[str, Any]: """simple docstring""" import tarfile UpperCAmelCase_ : Optional[int] = tmp_path_factory.mktemp("""data""" ) / """file.txt.tar""" with tarfile.TarFile(lowercase , """w""" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> int: """simple docstring""" import lzma UpperCAmelCase_ : List[Any] = tmp_path_factory.mktemp("""data""" ) / """file.txt.xz""" UpperCAmelCase_ : List[str] = bytes(lowercase , """utf-8""" ) with lzma.open(lowercase , """wb""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> Any: """simple docstring""" import zipfile UpperCAmelCase_ : Any = tmp_path_factory.mktemp("""data""" ) / """file.txt.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Dict: """simple docstring""" if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd UpperCAmelCase_ : List[str] = tmp_path_factory.mktemp("""data""" ) / """file.txt.zst""" UpperCAmelCase_ : Optional[int] = bytes(lowercase , """utf-8""" ) with zstd.open(lowercase , """wb""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Dict: """simple docstring""" UpperCAmelCase_ : int = tmp_path_factory.mktemp("""data""" ) / """file.xml""" UpperCAmelCase_ : int = textwrap.dedent( """\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <tmx version=\"1.4\"> <header segtype=\"sentence\" srclang=\"ca\" /> <body> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv> <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(lowercase , """w""" ) as f: f.write(lowercase ) return filename lowercase_ = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] lowercase_ = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] lowercase_ = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } lowercase_ = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] lowercase_ = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope="""session""" ) def A_ ( ) -> Union[str, Any]: """simple docstring""" return DATA_DICT_OF_LISTS @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : str = datasets.Dataset.from_dict(lowercase ) UpperCAmelCase_ : List[str] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.arrow""" ) dataset.map(cache_file_name=lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Dict = str(tmp_path_factory.mktemp("""data""" ) / """dataset.sqlite""" ) with contextlib.closing(sqlitea.connect(lowercase ) ) as con: UpperCAmelCase_ : Tuple = con.cursor() cur.execute("""CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)""" ) for item in DATA: cur.execute("""INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)""" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.csv""" ) with open(lowercase , """w""" , newline="""""" ) as f: UpperCAmelCase_ : Tuple = csv.DictWriter(lowercase , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.csv""" ) with open(lowercase , """w""" , newline="""""" ) as f: UpperCAmelCase_ : List[Any] = csv.DictWriter(lowercase , fieldnames=["""col_1""", """col_2""", """col_3"""] ) writer.writeheader() for item in DATA: writer.writerow(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> Optional[Any]: """simple docstring""" import bza UpperCAmelCase_ : List[Any] = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.bz2""" with open(lowercase , """rb""" ) as f: UpperCAmelCase_ : Dict = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(lowercase , """wb""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = tmp_path_factory.mktemp("""data""" ) / """dataset.csv.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename(csv_path.replace(""".csv""" , """.CSV""" ) ) ) f.write(lowercase , arcname=os.path.basename(csva_path.replace(""".csv""" , """.CSV""" ) ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.csv.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.join("""main_dir""" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("""main_dir""" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Any: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.parquet""" ) UpperCAmelCase_ : Dict = pa.schema( { """col_1""": pa.string(), """col_2""": pa.intaa(), """col_3""": pa.floataa(), } ) with open(lowercase , """wb""" ) as f: UpperCAmelCase_ : List[str] = pq.ParquetWriter(lowercase , schema=lowercase ) UpperCAmelCase_ : Any = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(lowercase ) )] for k in DATA[0]} , schema=lowercase ) writer.write_table(lowercase ) writer.close() return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) UpperCAmelCase_ : Union[str, Any] = {"""data""": DATA} with open(lowercase , """w""" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.json""" ) UpperCAmelCase_ : Optional[int] = {"""data""": DATA_DICT_OF_LISTS} with open(lowercase , """w""" ) as f: json.dump(lowercase , lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> str: """simple docstring""" UpperCAmelCase_ : List[str] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl""" ) with open(lowercase , """w""" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : str = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.jsonl""" ) with open(lowercase , """w""" ) as f: for item in DATA: f.write(json.dumps(lowercase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : int = str(tmp_path_factory.mktemp("""data""" ) / """dataset_312.jsonl""" ) with open(lowercase , """w""" ) as f: for item in DATA_312: f.write(json.dumps(lowercase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Dict = str(tmp_path_factory.mktemp("""data""" ) / """dataset-str.jsonl""" ) with open(lowercase , """w""" ) as f: for item in DATA_STR: f.write(json.dumps(lowercase ) + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> Dict: """simple docstring""" import gzip UpperCAmelCase_ : Dict = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt.gz""" ) with open(lowercase , """rb""" ) as orig_file: with gzip.open(lowercase , """wb""" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> str: """simple docstring""" import gzip UpperCAmelCase_ : Optional[Any] = str(tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.gz""" ) with open(lowercase , """rb""" ) as orig_file: with gzip.open(lowercase , """wb""" ) as zipped_file: zipped_file.writelines(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase , lowercase ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.join("""nested""" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.jsonl.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.join("""main_dir""" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("""main_dir""" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : int = tmp_path_factory.mktemp("""data""" ) / """dataset.jsonl.tar""" with tarfile.TarFile(lowercase , """w""" ) as f: f.add(lowercase , arcname=os.path.basename(lowercase ) ) f.add(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase , lowercase ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = tmp_path_factory.mktemp("""data""" ) / """dataset_nested.jsonl.tar""" with tarfile.TarFile(lowercase , """w""" ) as f: f.add(lowercase , arcname=os.path.join("""nested""" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Tuple = ["""0""", """1""", """2""", """3"""] UpperCAmelCase_ : str = str(tmp_path_factory.mktemp("""data""" ) / """dataset.txt""" ) with open(lowercase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = ["""0""", """1""", """2""", """3"""] UpperCAmelCase_ : int = str(tmp_path_factory.mktemp("""data""" ) / """dataset2.txt""" ) with open(lowercase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = ["""0""", """1""", """2""", """3"""] UpperCAmelCase_ : Optional[int] = tmp_path_factory.mktemp("""data""" ) / """dataset.abc""" with open(lowercase , """w""" ) as f: for item in data: f.write(item + """\n""" ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : Any = tmp_path_factory.mktemp("""data""" ) / """dataset.text.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = tmp_path_factory.mktemp("""data""" ) / """dataset_with_dir.text.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.join("""main_dir""" , os.path.basename(lowercase ) ) ) f.write(lowercase , arcname=os.path.join("""main_dir""" , os.path.basename(lowercase ) ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase , lowercase ) -> str: """simple docstring""" UpperCAmelCase_ : List[Any] = tmp_path_factory.mktemp("""data""" ) / """dataset.ext.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename("""unsupported.ext""" ) ) f.write(lowercase , arcname=os.path.basename("""unsupported_2.ext""" ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Tuple = """\n""".join(["""First""", """Second\u2029with Unicode new line""", """Third"""] ) UpperCAmelCase_ : List[Any] = str(tmp_path_factory.mktemp("""data""" ) / """dataset_with_unicode_new_lines.txt""" ) with open(lowercase , """w""" , encoding="""utf-8""" ) as f: f.write(lowercase ) return path @pytest.fixture(scope="""session""" ) def A_ ( ) -> Optional[int]: """simple docstring""" return os.path.join("""tests""" , """features""" , """data""" , """test_image_rgb.jpg""" ) @pytest.fixture(scope="""session""" ) def A_ ( ) -> Tuple: """simple docstring""" return os.path.join("""tests""" , """features""" , """data""" , """test_audio_44100.wav""" ) @pytest.fixture(scope="""session""" ) def A_ ( lowercase , lowercase ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = tmp_path_factory.mktemp("""data""" ) / """dataset.img.zip""" with zipfile.ZipFile(lowercase , """w""" ) as f: f.write(lowercase , arcname=os.path.basename(lowercase ) ) f.write(lowercase , arcname=os.path.basename(lowercase ).replace(""".jpg""" , """2.jpg""" ) ) return path @pytest.fixture(scope="""session""" ) def A_ ( lowercase ) -> Dict: """simple docstring""" UpperCAmelCase_ : Optional[int] = tmp_path_factory.mktemp("""data_dir""" ) (data_dir / "subdir").mkdir() with open(data_dir / """subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden file with open(data_dir / """subdir""" / """.test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / """.subdir""" / """train.txt""" , """w""" ) as f: f.write("""foo\n""" * 10 ) with open(data_dir / """.subdir""" / """test.txt""" , """w""" ) as f: f.write("""bar\n""" * 10 ) return data_dir
470
1
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A = logging.get_logger(__name__) A = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } A = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } A = {"facebook/blenderbot_small-90M": 512} def __UpperCAmelCase ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = set() UpperCAmelCase__ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCAmelCase__ = char UpperCAmelCase__ = set(__A ) return pairs class lowercase__ ( __SCREAMING_SNAKE_CASE ): A__= VOCAB_FILES_NAMES A__= PRETRAINED_VOCAB_FILES_MAP A__= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__= ['input_ids', 'attention_mask'] def __init__( self : Union[str, Any] , _lowercase : Optional[int] , _lowercase : List[str] , _lowercase : str="__start__" , _lowercase : List[Any]="__end__" , _lowercase : Dict="__unk__" , _lowercase : List[str]="__null__" , **_lowercase : int , ): """simple docstring""" super().__init__(unk_token=_lowercase , bos_token=_lowercase , eos_token=_lowercase , pad_token=_lowercase , **_lowercase ) with open(_lowercase , encoding="utf-8" ) as vocab_handle: UpperCAmelCase__ = json.load(_lowercase ) UpperCAmelCase__ = {v: k for k, v in self.encoder.items()} with open(_lowercase , encoding="utf-8" ) as merges_handle: UpperCAmelCase__ = merges_handle.read().split("\n" )[1:-1] UpperCAmelCase__ = [tuple(merge.split() ) for merge in merges] UpperCAmelCase__ = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) UpperCAmelCase__ = {} @property def _UpperCAmelCase ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def _UpperCAmelCase ( self : str ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def _UpperCAmelCase ( self : Dict , _lowercase : str ): """simple docstring""" if token in self.cache: return self.cache[token] UpperCAmelCase__ = re.sub("([.,!?()])" , r" \1" , _lowercase ) UpperCAmelCase__ = re.sub("(')" , r" \1 " , _lowercase ) UpperCAmelCase__ = re.sub(r"\s{2,}" , " " , _lowercase ) if "\n" in token: UpperCAmelCase__ = token.replace("\n" , " __newln__" ) UpperCAmelCase__ = token.split(" " ) UpperCAmelCase__ = [] for token in tokens: if not len(_lowercase ): continue UpperCAmelCase__ = token.lower() UpperCAmelCase__ = tuple(_lowercase ) UpperCAmelCase__ = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) UpperCAmelCase__ = get_pairs(_lowercase ) if not pairs: words.append(_lowercase ) continue while True: UpperCAmelCase__ = min(_lowercase , key=lambda _lowercase : self.bpe_ranks.get(_lowercase , float("inf" ) ) ) if bigram not in self.bpe_ranks: break UpperCAmelCase__ , UpperCAmelCase__ = bigram UpperCAmelCase__ = [] UpperCAmelCase__ = 0 while i < len(_lowercase ): try: UpperCAmelCase__ = word.index(_lowercase , _lowercase ) new_word.extend(word[i:j] ) UpperCAmelCase__ = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(_lowercase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCAmelCase__ = tuple(_lowercase ) UpperCAmelCase__ = new_word if len(_lowercase ) == 1: break else: UpperCAmelCase__ = get_pairs(_lowercase ) UpperCAmelCase__ = "@@ ".join(_lowercase ) UpperCAmelCase__ = word[:-4] UpperCAmelCase__ = word words.append(_lowercase ) return " ".join(_lowercase ) def _UpperCAmelCase ( self : Optional[int] , _lowercase : str ): """simple docstring""" UpperCAmelCase__ = [] UpperCAmelCase__ = re.findall(r"\S+\n?" , _lowercase ) for token in words: split_tokens.extend(list(self.bpe(_lowercase ).split(" " ) ) ) return split_tokens def _UpperCAmelCase ( self : List[str] , _lowercase : str ): """simple docstring""" UpperCAmelCase__ = token.lower() return self.encoder.get(_lowercase , self.encoder.get(self.unk_token ) ) def _UpperCAmelCase ( self : Any , _lowercase : int ): """simple docstring""" return self.decoder.get(_lowercase , self.unk_token ) def _UpperCAmelCase ( self : List[str] , _lowercase : List[str] ): """simple docstring""" UpperCAmelCase__ = " ".join(_lowercase ).replace("@@ " , "" ).strip() return out_string def _UpperCAmelCase ( self : Any , _lowercase : str , _lowercase : Optional[str] = None ): """simple docstring""" if not os.path.isdir(_lowercase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase__ = os.path.join( _lowercase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) UpperCAmelCase__ = os.path.join( _lowercase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_lowercase , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_lowercase , ensure_ascii=_lowercase ) + "\n" ) UpperCAmelCase__ = 0 with open(_lowercase , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _lowercase : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" " Please check that the tokenizer is not corrupted!" ) UpperCAmelCase__ = token_index writer.write(" ".join(_lowercase ) + "\n" ) index += 1 return vocab_file, merge_file
277
from __future__ import annotations def __UpperCAmelCase ( __A ) -> list[int]: '''simple docstring''' UpperCAmelCase__ = [True] * limit UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): UpperCAmelCase__ = i * 2 while index < limit: UpperCAmelCase__ = False UpperCAmelCase__ = index + i UpperCAmelCase__ = [2] for i in range(3 , __A , 2 ): if is_prime[i]: primes.append(__A ) return primes def __UpperCAmelCase ( __A = 1_0_0_0_0_0_0 ) -> int: '''simple docstring''' UpperCAmelCase__ = prime_sieve(__A ) UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 for i in range(len(__A ) ): for j in range(i + length , len(__A ) ): UpperCAmelCase__ = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: UpperCAmelCase__ = j - i UpperCAmelCase__ = sol return largest if __name__ == "__main__": print(f"{solution() = }")
277
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase ( unittest.TestCase ): def __init__( self : Any , UpperCAmelCase : Any , UpperCAmelCase : List[Any]=7 , UpperCAmelCase : Union[str, Any]=3 , UpperCAmelCase : int=18 , UpperCAmelCase : Optional[Any]=30 , UpperCAmelCase : Optional[Any]=400 , UpperCAmelCase : Tuple=True , UpperCAmelCase : Dict=None , UpperCAmelCase : Optional[Any]=True , ) -> Optional[Any]: lowerCamelCase__ : List[Any] = size if size is not None else {'height': 18, 'width': 18} lowerCamelCase__ : List[str] = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Union[str, Any] = num_channels lowerCamelCase__ : Optional[Any] = image_size lowerCamelCase__ : List[Any] = min_resolution lowerCamelCase__ : Optional[Any] = max_resolution lowerCamelCase__ : Optional[int] = do_resize lowerCamelCase__ : str = size lowerCamelCase__ : Union[str, Any] = apply_ocr def A_ ( self : List[str] ) -> List[str]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class lowerCAmelCase ( __UpperCamelCase, unittest.TestCase ): UpperCAmelCase__ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def A_ ( self : Optional[Any] ) -> Union[str, Any]: lowerCamelCase__ : Tuple = LayoutLMvaImageProcessingTester(self ) @property def A_ ( self : Union[str, Any] ) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def A_ ( self : List[Any] ) -> int: lowerCamelCase__ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'size' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'apply_ocr' ) ) def A_ ( self : List[Any] ) -> List[str]: lowerCamelCase__ : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) lowerCamelCase__ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def A_ ( self : Optional[int] ) -> Dict: pass def A_ ( self : Any ) -> str: # Initialize image_processing lowerCamelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase__ : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , Image.Image ) # Test not batched input lowerCamelCase__ : int = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase ) self.assertIsInstance(encoding.boxes , UpperCAmelCase ) # Test batched lowerCamelCase__ : Dict = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def A_ ( self : Dict ) -> Tuple: # Initialize image_processing lowerCamelCase__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , numpify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , np.ndarray ) # Test not batched input lowerCamelCase__ : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCamelCase__ : int = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def A_ ( self : List[str] ) -> List[Any]: # Initialize image_processing lowerCamelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , torchify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCamelCase__ : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCamelCase__ : List[Any] = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def A_ ( self : Optional[int] ) -> Dict: # with apply_OCR = True lowerCamelCase__ : Optional[int] = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCamelCase__ : Optional[Any] = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowerCamelCase__ : str = Image.open(ds[0]['file'] ).convert('RGB' ) lowerCamelCase__ : List[str] = image_processing(UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowerCamelCase__ : Tuple = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowerCamelCase__ : Optional[int] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase ) self.assertListEqual(encoding.boxes , UpperCAmelCase ) # with apply_OCR = False lowerCamelCase__ : Union[str, Any] = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase ) lowerCamelCase__ : str = image_processing(UpperCAmelCase , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
295
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _UpperCAmelCase : Optional[Any] = datasets.utils.logging.get_logger(__name__) @dataclass class lowerCAmelCase ( datasets.BuilderConfig ): UpperCAmelCase__ = 1_00_00 UpperCAmelCase__ = None UpperCAmelCase__ = None class lowerCAmelCase ( datasets.ArrowBasedBuilder ): UpperCAmelCase__ = ParquetConfig def A_ ( self : int ) -> Optional[int]: return datasets.DatasetInfo(features=self.config.features ) def A_ ( self : int , UpperCAmelCase : str ) -> Any: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) lowerCamelCase__ : List[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCAmelCase , (str, list, tuple) ): lowerCamelCase__ : int = data_files if isinstance(UpperCAmelCase , UpperCAmelCase ): lowerCamelCase__ : int = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase__ : str = [dl_manager.iter_files(UpperCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] lowerCamelCase__ : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(UpperCAmelCase , UpperCAmelCase ): lowerCamelCase__ : Optional[Any] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase__ : Dict = [dl_manager.iter_files(UpperCAmelCase ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(UpperCAmelCase ): with open(UpperCAmelCase , 'rb' ) as f: lowerCamelCase__ : Optional[Any] = datasets.Features.from_arrow_schema(pq.read_schema(UpperCAmelCase ) ) break splits.append(datasets.SplitGenerator(name=UpperCAmelCase , gen_kwargs={'files': files} ) ) return splits def A_ ( self : Optional[int] , UpperCAmelCase : pa.Table ) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowerCamelCase__ : Any = table_cast(UpperCAmelCase , self.info.features.arrow_schema ) return pa_table def A_ ( self : Any , UpperCAmelCase : Tuple ) -> List[str]: lowerCamelCase__ : Optional[Any] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'""" ) for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase ) ): with open(UpperCAmelCase , 'rb' ) as f: lowerCamelCase__ : List[Any] = pq.ParquetFile(UpperCAmelCase ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): lowerCamelCase__ : Tuple = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"""{file_idx}_{batch_idx}""", self._cast_table(UpperCAmelCase ) except ValueError as e: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase )}: {e}""" ) raise
295
1
def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if not isinstance(a_ , a_ ): A_ : Tuple = F"Input value of [number={number}] must be an integer" raise TypeError(a_ ) if number < 1: A_ : Union[str, Any] = F"Input value of [number={number}] must be > 0" raise ValueError(a_ ) A_ : Tuple = 1 for i in range(1 , a_ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
713
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def UpperCAmelCase ( a_ , a_=1 ) -> str: """simple docstring""" if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def UpperCAmelCase ( a_ , a_=0 ) -> Union[str, Any]: """simple docstring""" A_ : str = [] for old_item in old_list: A_ : List[str] = old_item.replace("""in_layers.0""" , """norm1""" ) A_ : Tuple = new_item.replace("""in_layers.2""" , """conv1""" ) A_ : List[Any] = new_item.replace("""out_layers.0""" , """norm2""" ) A_ : Dict = new_item.replace("""out_layers.3""" , """conv2""" ) A_ : int = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) A_ : Optional[int] = new_item.replace("""skip_connection""" , """conv_shortcut""" ) A_ : int = shave_segments(a_ , n_shave_prefix_segments=a_ ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def UpperCAmelCase ( a_ , a_=0 ) -> Union[str, Any]: """simple docstring""" A_ : Any = [] for old_item in old_list: A_ : Optional[int] = old_item A_ : Dict = new_item.replace("""norm.weight""" , """group_norm.weight""" ) A_ : Optional[int] = new_item.replace("""norm.bias""" , """group_norm.bias""" ) A_ : Union[str, Any] = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) A_ : Optional[Any] = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) A_ : Union[str, Any] = shave_segments(a_ , n_shave_prefix_segments=a_ ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def UpperCAmelCase ( a_ , a_ , a_ , a_=None , a_=None , a_=None ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): A_ : Optional[int] = old_checkpoint[path] A_ : Union[str, Any] = old_tensor.shape[0] // 3 A_ : Union[str, Any] = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) A_ : Any = old_tensor.shape[0] // config["""num_head_channels"""] // 3 A_ : Tuple = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) A_ , A_ , A_ : Tuple = old_tensor.split(channels // num_heads , dim=1 ) A_ : List[str] = query.reshape(a_ ) A_ : Union[str, Any] = key.reshape(a_ ) A_ : Optional[int] = value.reshape(a_ ) for path in paths: A_ : Optional[int] = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here A_ : Union[str, Any] = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) A_ : Any = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) A_ : Tuple = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: A_ : Union[str, Any] = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: A_ : Tuple = old_checkpoint[path["""old"""]][:, :, 0] else: A_ : Optional[int] = old_checkpoint[path["""old"""]] def UpperCAmelCase ( a_ , a_ ) -> Optional[int]: """simple docstring""" A_ : Optional[Any] = {} A_ : Dict = checkpoint["""time_embed.0.weight"""] A_ : Dict = checkpoint["""time_embed.0.bias"""] A_ : Optional[Any] = checkpoint["""time_embed.2.weight"""] A_ : Tuple = checkpoint["""time_embed.2.bias"""] A_ : List[Any] = checkpoint["""input_blocks.0.0.weight"""] A_ : List[str] = checkpoint["""input_blocks.0.0.bias"""] A_ : Any = checkpoint["""out.0.weight"""] A_ : Any = checkpoint["""out.0.bias"""] A_ : Optional[int] = checkpoint["""out.2.weight"""] A_ : int = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only A_ : List[Any] = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) A_ : Optional[int] = { layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(a_ ) } # Retrieves the keys for the middle blocks only A_ : Optional[int] = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) A_ : Optional[int] = { layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(a_ ) } # Retrieves the keys for the output blocks only A_ : str = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) A_ : Any = { layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(a_ ) } for i in range(1 , a_ ): A_ : int = (i - 1) // (config["""num_res_blocks"""] + 1) A_ : Optional[int] = (i - 1) % (config["""num_res_blocks"""] + 1) A_ : Dict = [key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] A_ : List[str] = [key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: A_ : List[Any] = checkpoint[ F"input_blocks.{i}.0.op.weight" ] A_ : Optional[Any] = checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue A_ : Optional[Any] = renew_resnet_paths(a_ ) A_ : Dict = {"""old""": F"input_blocks.{i}.0", """new""": F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} A_ : str = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( a_ , a_ , a_ , additional_replacements=[meta_path, resnet_op] , config=a_ ) if len(a_ ): A_ : Any = renew_attention_paths(a_ ) A_ : Any = { """old""": F"input_blocks.{i}.1", """new""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } A_ : List[Any] = { F"input_blocks.{i}.1.qkv.bias": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( a_ , a_ , a_ , additional_replacements=[meta_path] , attention_paths_to_split=a_ , config=a_ , ) A_ : Tuple = middle_blocks[0] A_ : Optional[int] = middle_blocks[1] A_ : int = middle_blocks[2] A_ : int = renew_resnet_paths(a_ ) assign_to_checkpoint(a_ , a_ , a_ , config=a_ ) A_ : Tuple = renew_resnet_paths(a_ ) assign_to_checkpoint(a_ , a_ , a_ , config=a_ ) A_ : Optional[int] = renew_attention_paths(a_ ) A_ : Optional[int] = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( a_ , a_ , a_ , attention_paths_to_split=a_ , config=a_ ) for i in range(a_ ): A_ : Union[str, Any] = i // (config["""num_res_blocks"""] + 1) A_ : Union[str, Any] = i % (config["""num_res_blocks"""] + 1) A_ : List[str] = [shave_segments(a_ , 2 ) for name in output_blocks[i]] A_ : Union[str, Any] = {} for layer in output_block_layers: A_ , A_ : List[str] = layer.split(""".""" )[0], shave_segments(a_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(a_ ) else: A_ : Optional[int] = [layer_name] if len(a_ ) > 1: A_ : List[str] = [key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] A_ : List[Any] = [key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] A_ : str = renew_resnet_paths(a_ ) A_ : Dict = renew_resnet_paths(a_ ) A_ : Tuple = {"""old""": F"output_blocks.{i}.0", """new""": F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(a_ , a_ , a_ , additional_replacements=[meta_path] , config=a_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): A_ : List[Any] = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) A_ : Optional[Any] = checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] A_ : Any = checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(a_ ) == 2: A_ : int = [] if len(a_ ): A_ : Union[str, Any] = renew_attention_paths(a_ ) A_ : Optional[int] = { """old""": F"output_blocks.{i}.1", """new""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } A_ : str = { F"output_blocks.{i}.1.qkv.bias": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( a_ , a_ , a_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=a_ , ) else: A_ : List[str] = renew_resnet_paths(a_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: A_ : List[str] = """.""".join(["""output_blocks""", str(a_ ), path["""old"""]] ) A_ : int = """.""".join(["""up_blocks""", str(a_ ), """resnets""", str(a_ ), path["""new"""]] ) A_ : Tuple = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') UpperCamelCase__ : Tuple = parser.parse_args() UpperCamelCase__ : Union[str, Any] = torch.load(args.checkpoint_path) with open(args.config_file) as f: UpperCamelCase__ : Any = json.loads(f.read()) UpperCamelCase__ : Any = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] UpperCamelCase__ : List[str] = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: UpperCamelCase__ : Dict = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) UpperCamelCase__ : List[Any] = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) UpperCamelCase__ : str = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
385
0
'''simple docstring''' import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str=100 , lowerCAmelCase__ : str=13 , lowerCAmelCase__ : Optional[Any]=30 , lowerCAmelCase__ : Tuple=2 , lowerCAmelCase__ : Optional[int]=3 , lowerCAmelCase__ : List[Any]=True , lowerCAmelCase__ : int=True , lowerCAmelCase__ : Optional[Any]=32 , lowerCAmelCase__ : int=5 , lowerCAmelCase__ : str=4 , lowerCAmelCase__ : Tuple=37 , lowerCAmelCase__ : Optional[int]="gelu" , lowerCAmelCase__ : Tuple=0.1 , lowerCAmelCase__ : List[str]=0.1 , lowerCAmelCase__ : Tuple=10 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : List[str]=3 , ) -> Optional[int]: '''simple docstring''' _UpperCamelCase = parent _UpperCamelCase = vocab_size _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 # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _UpperCamelCase = (image_size // patch_size) ** 2 _UpperCamelCase = num_patches + 1 def snake_case__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' _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 = BeitConfig( vocab_size=self.vocab_size , 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=lowerCAmelCase__ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def snake_case__ ( self : Union[str, Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : int ) -> Any: '''simple docstring''' _UpperCamelCase = FlaxBeitModel(config=lowerCAmelCase__ ) _UpperCamelCase = model(lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case__ ( self : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any ) -> List[str]: '''simple docstring''' _UpperCamelCase = FlaxBeitForMaskedImageModeling(config=lowerCAmelCase__ ) _UpperCamelCase = model(lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def snake_case__ ( self : str , lowerCAmelCase__ : str , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int ) -> Any: '''simple docstring''' _UpperCamelCase = self.type_sequence_label_size _UpperCamelCase = FlaxBeitForImageClassification(config=lowerCAmelCase__ ) _UpperCamelCase = model(lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _UpperCamelCase = 1 _UpperCamelCase = FlaxBeitForImageClassification(lowerCAmelCase__ ) _UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _UpperCamelCase = model(lowerCAmelCase__ ) def snake_case__ ( self : int ) -> Dict: '''simple docstring''' _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" _snake_case : Optional[int] = ( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def snake_case__ ( self : List[Any] ) -> None: '''simple docstring''' _UpperCamelCase = FlaxBeitModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ , hidden_size=37 ) def snake_case__ ( self : Any ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def snake_case__ ( self : Optional[int] ) -> str: '''simple docstring''' _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase = model_class(lowerCAmelCase__ ) _UpperCamelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase = [*signature.parameters.keys()] _UpperCamelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def snake_case__ ( self : int ) -> Optional[Any]: '''simple docstring''' _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _UpperCamelCase = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCamelCase = model_class(lowerCAmelCase__ ) @jax.jit def model_jitted(lowerCAmelCase__ : Tuple , **lowerCAmelCase__ : str ): return model(pixel_values=lowerCAmelCase__ , **lowerCAmelCase__ ) with self.subTest('''JIT Enabled''' ): _UpperCamelCase = model_jitted(**lowerCAmelCase__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _UpperCamelCase = model_jitted(**lowerCAmelCase__ ).to_tuple() self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) ) for jitted_output, output in zip(lowerCAmelCase__ , lowerCAmelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def snake_case__ ( self : Union[str, Any] ) -> str: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def snake_case__ ( self : Any ) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__ ) def snake_case__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) @slow def snake_case__ ( self : int ) -> int: '''simple docstring''' for model_class_name in self.all_model_classes: _UpperCamelCase = model_class_name.from_pretrained('''microsoft/beit-base-patch16-224''' ) _UpperCamelCase = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(lowerCAmelCase__ ) def a__ ( ) -> Optional[Any]: """simple docstring""" _UpperCamelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @require_flax class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224''' ) if is_vision_available() else None @slow def snake_case__ ( self : Optional[Any] ) -> Dict: '''simple docstring''' _UpperCamelCase = FlaxBeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''' ) _UpperCamelCase = self.default_image_processor _UpperCamelCase = prepare_img() _UpperCamelCase = image_processor(images=lowerCAmelCase__ , return_tensors='''np''' ).pixel_values # prepare bool_masked_pos _UpperCamelCase = np.ones((1, 196) , dtype=lowerCAmelCase__ ) # forward pass _UpperCamelCase = model(pixel_values=lowerCAmelCase__ , bool_masked_pos=lowerCAmelCase__ ) _UpperCamelCase = outputs.logits # verify the logits _UpperCamelCase = (1, 196, 8192) self.assertEqual(logits.shape , lowerCAmelCase__ ) _UpperCamelCase = np.array( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , lowerCAmelCase__ , atol=1e-2 ) ) @slow def snake_case__ ( self : str ) -> List[Any]: '''simple docstring''' _UpperCamelCase = FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''' ) _UpperCamelCase = self.default_image_processor _UpperCamelCase = prepare_img() _UpperCamelCase = image_processor(images=lowerCAmelCase__ , return_tensors='''np''' ) # forward pass _UpperCamelCase = model(**lowerCAmelCase__ ) _UpperCamelCase = outputs.logits # verify the logits _UpperCamelCase = (1, 1000) self.assertEqual(logits.shape , lowerCAmelCase__ ) _UpperCamelCase = np.array([-1.2385, -1.0987, -1.0108] ) self.assertTrue(np.allclose(logits[0, :3] , lowerCAmelCase__ , atol=1e-4 ) ) _UpperCamelCase = 281 self.assertEqual(logits.argmax(-1 ).item() , lowerCAmelCase__ ) @slow def snake_case__ ( self : Tuple ) -> Tuple: '''simple docstring''' _UpperCamelCase = FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''' ) _UpperCamelCase = self.default_image_processor _UpperCamelCase = prepare_img() _UpperCamelCase = image_processor(images=lowerCAmelCase__ , return_tensors='''np''' ) # forward pass _UpperCamelCase = model(**lowerCAmelCase__ ) _UpperCamelCase = outputs.logits # verify the logits _UpperCamelCase = (1, 21841) self.assertEqual(logits.shape , lowerCAmelCase__ ) _UpperCamelCase = np.array([1.6881, -0.2787, 0.5901] ) self.assertTrue(np.allclose(logits[0, :3] , lowerCAmelCase__ , atol=1e-4 ) ) _UpperCamelCase = 2396 self.assertEqual(logits.argmax(-1 ).item() , lowerCAmelCase__ )
98
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Tuple: if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__UpperCamelCase , n - 1 , __UpperCamelCase ) * a) % mod else: UpperCamelCase = binary_exponentiation(__UpperCamelCase , n / 2 , __UpperCamelCase ) return (b * b) % mod # a prime number SCREAMING_SNAKE_CASE__ = 7_0_1 SCREAMING_SNAKE_CASE__ = 1_0_0_0_0_0_0_0_0_0 SCREAMING_SNAKE_CASE__ = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
301
0
def __lowerCAmelCase ( UpperCamelCase ) -> bool: if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(UpperCamelCase ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(UpperCamelCase ) == 1: return True lowerCAmelCase__ : Tuple = series[1] - series[0] for index in range(len(UpperCamelCase ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def __lowerCAmelCase ( UpperCamelCase ) -> float: if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(UpperCamelCase ) == 0: raise ValueError('''Input list must be a non empty list''' ) lowerCAmelCase__ : int = 0 for val in series: answer += val return answer / len(UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
470
import numpy as np class _lowerCAmelCase : def __init__( self ): lowerCAmelCase__ : List[Any] = (0, 0) lowerCAmelCase__ : Optional[int] = None lowerCAmelCase__ : Optional[Any] = 0 lowerCAmelCase__ : Optional[int] = 0 lowerCAmelCase__ : Tuple = 0 def __eq__( self , __UpperCAmelCase ): return self.position == cell.position def __magic_name__( self ): print(self.position ) class _lowerCAmelCase : def __init__( self , __UpperCAmelCase=(5, 5) ): lowerCAmelCase__ : List[str] = np.zeros(__UpperCAmelCase ) lowerCAmelCase__ : List[Any] = world_size[0] lowerCAmelCase__ : str = world_size[1] def __magic_name__( self ): print(self.w ) def __magic_name__( self , __UpperCAmelCase ): lowerCAmelCase__ : Optional[Any] = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] lowerCAmelCase__ : Tuple = cell.position[0] lowerCAmelCase__ : Optional[int] = cell.position[1] lowerCAmelCase__ : Any = [] for n in neughbour_cord: lowerCAmelCase__ : int = current_x + n[0] lowerCAmelCase__ : Dict = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: lowerCAmelCase__ : Optional[int] = Cell() lowerCAmelCase__ : Optional[int] = (x, y) lowerCAmelCase__ : Any = cell neighbours.append(__UpperCAmelCase ) return neighbours def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: lowerCAmelCase__ : int = [] lowerCAmelCase__ : int = [] _open.append(UpperCamelCase ) while _open: lowerCAmelCase__ : Dict = np.argmin([n.f for n in _open] ) lowerCAmelCase__ : Dict = _open[min_f] _closed.append(_open.pop(UpperCamelCase ) ) if current == goal: break for n in world.get_neigbours(UpperCamelCase ): for c in _closed: if c == n: continue lowerCAmelCase__ : Any = current.g + 1 lowerCAmelCase__ , lowerCAmelCase__ : int = n.position lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = goal.position lowerCAmelCase__ : Tuple = (ya - ya) ** 2 + (xa - xa) ** 2 lowerCAmelCase__ : Optional[Any] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(UpperCamelCase ) lowerCAmelCase__ : List[Any] = [] while current.parent is not None: path.append(current.position ) lowerCAmelCase__ : List[Any] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowerCAmelCase_ = Gridworld() # Start position and goal lowerCAmelCase_ = Cell() lowerCAmelCase_ = (0, 0) lowerCAmelCase_ = Cell() lowerCAmelCase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowerCAmelCase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowerCAmelCase_ = 1 print(world.w)
470
1
'''simple docstring''' def lowerCamelCase ( lowerCAmelCase : list[int] , lowerCAmelCase : int ): """simple docstring""" __magic_name__ : int = len(__lowerCAmelCase ) __magic_name__ : Any = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __magic_name__ : int = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): __magic_name__ : Tuple = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: __magic_name__ : Optional[int] = subset[i - 1][j] if arr[i - 1] <= j: __magic_name__ : int = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
561
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def A__ ( __lowerCAmelCase : Any ): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0x4_e_0_0 and cp <= 0x9_f_f_f) or (cp >= 0x3_4_0_0 and cp <= 0x4_d_b_f) # or (cp >= 0x2_0_0_0_0 and cp <= 0x2_a_6_d_f) # or (cp >= 0x2_a_7_0_0 and cp <= 0x2_b_7_3_f) # or (cp >= 0x2_b_7_4_0 and cp <= 0x2_b_8_1_f) # or (cp >= 0x2_b_8_2_0 and cp <= 0x2_c_e_a_f) # or (cp >= 0xf_9_0_0 and cp <= 0xf_a_f_f) or (cp >= 0x2_f_8_0_0 and cp <= 0x2_f_a_1_f) # ): # return True return False def A__ ( __lowerCAmelCase : str ): # word like '180' or '身高' or '神' for char in word: lowerCamelCase__ = ord(__lowerCAmelCase ) if not _is_chinese_char(__lowerCAmelCase ): return 0 return 1 def A__ ( __lowerCAmelCase : List[str] ): lowerCamelCase__ = set() for token in tokens: lowerCamelCase__ = len(__lowerCAmelCase ) > 1 and is_chinese(__lowerCAmelCase ) if chinese_word: word_set.add(__lowerCAmelCase ) lowerCamelCase__ = list(__lowerCAmelCase ) return word_list def A__ ( __lowerCAmelCase : List[str] , __lowerCAmelCase : set() ): if not chinese_word_set: return bert_tokens lowerCamelCase__ = max([len(__lowerCAmelCase ) for w in chinese_word_set] ) lowerCamelCase__ = bert_tokens lowerCamelCase__ , lowerCamelCase__ = 0, len(__lowerCAmelCase ) while start < end: lowerCamelCase__ = True if is_chinese(bert_word[start] ): lowerCamelCase__ = min(end - start , __lowerCAmelCase ) for i in range(__lowerCAmelCase , 1 , -1 ): lowerCamelCase__ = """""".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): lowerCamelCase__ = """##""" + bert_word[j] lowerCamelCase__ = start + i lowerCamelCase__ = False break if single_word: start += 1 return bert_word def A__ ( __lowerCAmelCase : List[str] , __lowerCAmelCase : LTP , __lowerCAmelCase : BertTokenizer ): lowerCamelCase__ = [] for i in range(0 , len(__lowerCAmelCase ) , 100 ): lowerCamelCase__ = ltp_tokenizer.pipeline(lines[i : i + 100] , tasks=["""cws"""] ).cws lowerCamelCase__ = [get_chinese_word(__lowerCAmelCase ) for r in res] ltp_res.extend(__lowerCAmelCase ) assert len(__lowerCAmelCase ) == len(__lowerCAmelCase ) lowerCamelCase__ = [] for i in range(0 , len(__lowerCAmelCase ) , 100 ): lowerCamelCase__ = bert_tokenizer(lines[i : i + 100] , add_special_tokens=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=512 ) bert_res.extend(res["""input_ids"""] ) assert len(__lowerCAmelCase ) == len(__lowerCAmelCase ) lowerCamelCase__ = [] for input_ids, chinese_word in zip(__lowerCAmelCase , __lowerCAmelCase ): lowerCamelCase__ = [] for id in input_ids: lowerCamelCase__ = bert_tokenizer._convert_id_to_token(__lowerCAmelCase ) input_tokens.append(__lowerCAmelCase ) lowerCamelCase__ = add_sub_symbol(__lowerCAmelCase , __lowerCAmelCase ) lowerCamelCase__ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__lowerCAmelCase ): if token[:2] == "##": lowerCamelCase__ = token[2:] # save chinese tokens' pos if len(__lowerCAmelCase ) == 1 and _is_chinese_char(ord(__lowerCAmelCase ) ): ref_id.append(__lowerCAmelCase ) ref_ids.append(__lowerCAmelCase ) assert len(__lowerCAmelCase ) == len(__lowerCAmelCase ) return ref_ids def A__ ( __lowerCAmelCase : Optional[int] ): # For Chinese (Ro)Bert, the best result is from : RoBERTa-wwm-ext (https://github.com/ymcui/Chinese-BERT-wwm) # If we want to fine-tune these model, we have to use same tokenizer : LTP (https://github.com/HIT-SCIR/ltp) with open(args.file_name , """r""" , encoding="""utf-8""" ) as f: lowerCamelCase__ = f.readlines() lowerCamelCase__ = [line.strip() for line in data if len(__lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' lowerCamelCase__ = LTP(args.ltp ) # faster in GPU device lowerCamelCase__ = BertTokenizer.from_pretrained(args.bert ) lowerCamelCase__ = prepare_ref(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) with open(args.save_path , """w""" , encoding="""utf-8""" ) as f: lowerCamelCase__ = [json.dumps(__lowerCAmelCase ) + """\n""" for ref in ref_ids] f.writelines(__lowerCAmelCase ) if __name__ == "__main__": UpperCamelCase : Optional[int] = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', required=False, type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', required=False, type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path', ) parser.add_argument( '--bert', required=False, type=str, default='./resources/robert', help='resources for Bert tokenizer', ) parser.add_argument( '--save_path', required=False, type=str, default='./resources/ref.txt', help='path to save res', ) UpperCamelCase : Any = parser.parse_args() main(args)
50
0
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class lowerCAmelCase_ : lowerCamelCase_ = 42 # [batch_size x 3] lowerCamelCase_ = 42 # [batch_size x 3] lowerCamelCase_ = 42 # [batch_size x 3] lowerCamelCase_ = 42 # [batch_size x 3] lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 def _snake_case ( self : Dict ) ->Optional[Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def _snake_case ( self : str ) ->Dict: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def _snake_case ( self : List[str] ) ->str: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def _snake_case ( self : List[str] ) ->torch.Tensor: """simple docstring""" a__ :Union[str, Any] = torch.arange(self.height * self.width ) a__ :List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(__A , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def _snake_case ( self : List[str] ) ->Tuple: """simple docstring""" a__ , *a__ :int = self.shape a__ :Any = int(np.prod(__A ) ) a__ :List[Any] = self.get_image_coords() a__ :List[str] = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) a__ :Union[str, Any] = self.get_camera_rays(__A ) a__ :Optional[int] = rays.view(__A , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def _snake_case ( self : Optional[Any] , __A : torch.Tensor ) ->torch.Tensor: """simple docstring""" a__ , *a__ , a__ :str = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] a__ :Optional[int] = coords.view(__A , -1 , 2 ) a__ :Optional[int] = self.resolution() a__ :Union[str, Any] = self.fov() a__ :List[str] = (flat.float() / (res - 1)) * 2 - 1 a__ :int = fracs * torch.tan(fov / 2 ) a__ :Optional[Any] = fracs.view(__A , -1 , 2 ) a__ :int = ( self.z.view(__A , 1 , 3 ) + self.x.view(__A , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__A , 1 , 3 ) * fracs[:, :, 1:] ) a__ :Tuple = directions / directions.norm(dim=-1 , keepdim=__A ) a__ :str = torch.stack( [ torch.broadcast_to(self.origin.view(__A , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__A , *__A , 2 , 3 ) def _snake_case ( self : List[Any] , __A : int , __A : int ) ->"DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__A , height=__A , x_fov=self.x_fov , y_fov=self.y_fov , ) def lowerCamelCase__ ( a : int ) -> DifferentiableProjectiveCamera: """simple docstring""" a__ :Dict = [] a__ :Any = [] a__ :Optional[int] = [] a__ :List[Any] = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): a__ :Optional[int] = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) a__ :str = -z * 4 a__ :List[Any] = np.array([np.cos(a ), -np.sin(a ), 0.0] ) a__ :Tuple = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
373
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version snake_case__ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def lowerCamelCase__ ( a : np.ndarray , a : float , a : int = 16_000 ) -> List[str]: """simple docstring""" a__ :Optional[int] = int(round(sample_rate * max_length ) ) if len(a ) <= sample_length: return wav a__ :Optional[Any] = randint(0 , len(a ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class lowerCAmelCase_ : lowerCamelCase_ = field(default=_a ,metadata={'help': 'Name of a dataset from the datasets package'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'A file containing the training audio paths and labels.'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'A file containing the validation audio paths and labels.'}) lowerCamelCase_ = field( default='train' ,metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } ,) lowerCamelCase_ = field( default='validation' ,metadata={ 'help': ( 'The name of the training data set split to use (via the datasets library). Defaults to \'validation\'' ) } ,) lowerCamelCase_ = field( default='audio' ,metadata={'help': 'The name of the dataset column containing the audio data. Defaults to \'audio\''} ,) lowerCamelCase_ = field( default='label' ,metadata={'help': 'The name of the dataset column containing the labels. Defaults to \'label\''}) lowerCamelCase_ = field( default=_a ,metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } ,) lowerCamelCase_ = field( default=_a ,metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } ,) lowerCamelCase_ = field( default=20 ,metadata={'help': 'Audio clips will be randomly cut to this length during training if the value is set.'} ,) @dataclass class lowerCAmelCase_ : lowerCamelCase_ = field( default='facebook/wav2vec2-base' ,metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ,) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Pretrained config name or path if not the same as model_name'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Where do you want to store the pretrained models downloaded from the Hub'}) lowerCamelCase_ = field( default='main' ,metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} ,) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Name or path of preprocessor config.'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Whether to freeze the feature encoder layers of the model.'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Whether to generate an attention mask in the feature extractor.'}) lowerCamelCase_ = field( default=_a ,metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } ,) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}) lowerCamelCase_ = field( default=_a ,metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} ,) def _snake_case ( self : Optional[Any] ) ->Dict: """simple docstring""" if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( "The argument `--freeze_feature_extractor` is deprecated and " "will be removed in a future version. Use `--freeze_feature_encoder`" "instead. Setting `freeze_feature_encoder==True`." , __A , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( "The argument `--freeze_feature_extractor` is deprecated and " "should not be used in combination with `--freeze_feature_encoder`." "Only make use of `--freeze_feature_encoder`." ) def lowerCamelCase__ ( ) -> Optional[Any]: """simple docstring""" # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. a__ :Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. a__ , a__ , a__ :int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: a__ , a__ , a__ :Union[str, Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_audio_classification" , a , a ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() a__ :Union[str, Any] = training_args.get_process_log_level() logger.setLevel(a ) transformers.utils.logging.set_verbosity(a ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. a__ :List[str] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: a__ :List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to train from scratch." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Initialize our dataset and prepare it for the audio classification task. a__ :List[str] = DatasetDict() a__ :int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) a__ :List[str] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'''--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ''' "Make sure to set `--audio_column_name` to the correct audio column - one of " F'''{', '.join(raw_datasets['train'].column_names )}.''' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'''--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ''' "Make sure to set `--label_column_name` to the correct text column - one of " F'''{', '.join(raw_datasets['train'].column_names )}.''' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy a__ :str = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. a__ :List[Any] = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) a__ :Optional[Any] = feature_extractor.model_input_names[0] def train_transforms(a : Union[str, Any] ): a__ :List[str] = [] for audio in batch[data_args.audio_column_name]: a__ :List[Any] = random_subsample( audio["array"] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(a ) a__ :Dict = feature_extractor(a , sampling_rate=feature_extractor.sampling_rate ) a__ :Dict = {model_input_name: inputs.get(a )} a__ :Union[str, Any] = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(a : Optional[int] ): a__ :Any = [audio["array"] for audio in batch[data_args.audio_column_name]] a__ :int = feature_extractor(a , sampling_rate=feature_extractor.sampling_rate ) a__ :int = {model_input_name: inputs.get(a )} a__ :Dict = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. a__ :Union[str, Any] = raw_datasets["train"].features[data_args.label_column_name].names a__ , a__ :str = {}, {} for i, label in enumerate(a ): a__ :Tuple = str(a ) a__ :List[str] = label # Load the accuracy metric from the datasets package a__ :Optional[int] = evaluate.load("accuracy" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(a : List[Any] ): a__ :str = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=a , references=eval_pred.label_ids ) a__ :Dict = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(a ) , labelaid=a , idalabel=a , finetuning_task="audio-classification" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) a__ :Any = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: a__ :Tuple = ( raw_datasets["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(a , output_all_columns=a ) if training_args.do_eval: if data_args.max_eval_samples is not None: a__ :Optional[int] = ( raw_datasets["eval"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(a , output_all_columns=a ) # Initialize our trainer a__ :List[str] = Trainer( model=a , args=a , train_dataset=raw_datasets["train"] if training_args.do_train else None , eval_dataset=raw_datasets["eval"] if training_args.do_eval else None , compute_metrics=a , tokenizer=a , ) # Training if training_args.do_train: a__ :Tuple = None if training_args.resume_from_checkpoint is not None: a__ :List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: a__ :Any = last_checkpoint a__ :Any = trainer.train(resume_from_checkpoint=a ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: a__ :int = trainer.evaluate() trainer.log_metrics("eval" , a ) trainer.save_metrics("eval" , a ) # Write model card and (optionally) push to hub a__ :str = { "finetuned_from": model_args.model_name_or_path, "tasks": "audio-classification", "dataset": data_args.dataset_name, "tags": ["audio-classification"], } if training_args.push_to_hub: trainer.push_to_hub(**a ) else: trainer.create_model_card(**a ) if __name__ == "__main__": main()
373
1
"""simple docstring""" import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } __SCREAMING_SNAKE_CASE = { """vocab_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json""" }, """merges_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt""" }, """tokenizer_config_file""": { """facebook/blenderbot_small-90M""": ( """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json""" ) }, } __SCREAMING_SNAKE_CASE = {"""facebook/blenderbot_small-90M""": 5_12} def UpperCAmelCase ( a__ ): '''simple docstring''' lowerCAmelCase :List[str] = set() lowerCAmelCase :List[str] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCAmelCase :Optional[int] = char lowerCAmelCase :List[str] = set(snake_case_ ) return pairs class __UpperCamelCase ( a_ ): lowercase_ : str = VOCAB_FILES_NAMES lowercase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowercase_ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : str = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : str , UpperCAmelCase : Dict="__start__" , UpperCAmelCase : Optional[Any]="__end__" , UpperCAmelCase : str="__unk__" , UpperCAmelCase : int="__null__" , **UpperCAmelCase : Union[str, Any] , ) -> Union[str, Any]: super().__init__(unk_token=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , pad_token=__lowerCamelCase , **__lowerCamelCase ) with open(__lowerCamelCase , encoding='utf-8' ) as vocab_handle: lowerCAmelCase :str = json.load(__lowerCamelCase ) lowerCAmelCase :Union[str, Any] = {v: k for k, v in self.encoder.items()} with open(__lowerCamelCase , encoding='utf-8' ) as merges_handle: lowerCAmelCase :Any = merges_handle.read().split('\n' )[1:-1] lowerCAmelCase :int = [tuple(merge.split() ) for merge in merges] lowerCAmelCase :Any = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) lowerCAmelCase :str = {} @property def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: return len(self.encoder ) def UpperCAmelCase__ ( self : Optional[Any] ) -> int: return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self : List[str] , UpperCAmelCase : str ) -> int: if token in self.cache: return self.cache[token] lowerCAmelCase :Optional[int] = re.sub('([.,!?()])' , r' \1' , __lowerCamelCase ) lowerCAmelCase :Union[str, Any] = re.sub('(\')' , r' \1 ' , __lowerCamelCase ) lowerCAmelCase :Any = re.sub(r'\s{2,}' , ' ' , __lowerCamelCase ) if "\n" in token: lowerCAmelCase :Optional[Any] = token.replace('\n' , ' __newln__' ) lowerCAmelCase :Optional[int] = token.split(' ' ) lowerCAmelCase :int = [] for token in tokens: if not len(__lowerCamelCase ): continue lowerCAmelCase :int = token.lower() lowerCAmelCase :Optional[int] = tuple(__lowerCamelCase ) lowerCAmelCase :Dict = tuple(list(word[:-1] ) + [word[-1] + '</w>'] ) lowerCAmelCase :Dict = get_pairs(__lowerCamelCase ) if not pairs: words.append(__lowerCamelCase ) continue while True: lowerCAmelCase :Dict = min(__lowerCamelCase , key=lambda UpperCAmelCase : self.bpe_ranks.get(__lowerCamelCase , float('inf' ) ) ) if bigram not in self.bpe_ranks: break lowerCAmelCase , lowerCAmelCase :int = bigram lowerCAmelCase :Any = [] lowerCAmelCase :Dict = 0 while i < len(__lowerCamelCase ): try: lowerCAmelCase :Tuple = word.index(__lowerCamelCase , __lowerCamelCase ) new_word.extend(word[i:j] ) lowerCAmelCase :int = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCAmelCase :Union[str, Any] = tuple(__lowerCamelCase ) lowerCAmelCase :Dict = new_word if len(__lowerCamelCase ) == 1: break else: lowerCAmelCase :Tuple = get_pairs(__lowerCamelCase ) lowerCAmelCase :List[str] = '@@ '.join(__lowerCamelCase ) lowerCAmelCase :Any = word[:-4] lowerCAmelCase :Union[str, Any] = word words.append(__lowerCamelCase ) return " ".join(__lowerCamelCase ) def UpperCAmelCase__ ( self : Optional[Any] , UpperCAmelCase : str ) -> Tuple: lowerCAmelCase :Optional[Any] = [] lowerCAmelCase :Optional[int] = re.findall(r'\S+\n?' , __lowerCamelCase ) for token in words: split_tokens.extend(list(self.bpe(__lowerCamelCase ).split(' ' ) ) ) return split_tokens def UpperCAmelCase__ ( self : Tuple , UpperCAmelCase : str ) -> List[str]: lowerCAmelCase :str = token.lower() return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self : List[str] , UpperCAmelCase : int ) -> Union[str, Any]: return self.decoder.get(__lowerCamelCase , self.unk_token ) def UpperCAmelCase__ ( self : Any , UpperCAmelCase : List[str] ) -> Optional[int]: lowerCAmelCase :int = ' '.join(__lowerCamelCase ).replace('@@ ' , '' ).strip() return out_string def UpperCAmelCase__ ( self : Dict , UpperCAmelCase : str , UpperCAmelCase : Optional[str] = None ) -> List[Any]: if not os.path.isdir(__lowerCamelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase :Optional[Any] = os.path.join( __lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) lowerCAmelCase :List[str] = os.path.join( __lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(__lowerCamelCase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + '\n' ) lowerCAmelCase :str = 0 with open(__lowerCamelCase , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCAmelCase : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) lowerCAmelCase :int = token_index writer.write(' '.join(__lowerCamelCase ) + '\n' ) index += 1 return vocab_file, merge_file
553
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCamelCase__ : Tuple = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCamelCase__ : Union[str, Any] = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCamelCase__ : Any = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase_ ( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' ,id='''token''' ) ,id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' ,id='''token''' ) ,id='''sequence''' ) ,id='''references''' ), } ) ,) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[List[List[str]]] ,__lowerCamelCase : List[List[str]] ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 4 ,): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=__lowerCamelCase ,hypotheses=__lowerCamelCase ,min_len=__lowerCamelCase ,max_len=__lowerCamelCase ) }
387
0
'''simple docstring''' from ...processing_utils import ProcessorMixin class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __a : Optional[Any] = "WhisperFeatureExtractor" __a : Any = "WhisperTokenizer" def __init__( self : Any , lowercase : Tuple , lowercase : Union[str, Any] ) -> List[Any]: '''simple docstring''' super().__init__(lowercase , lowercase ) UpperCamelCase__ = self.feature_extractor UpperCamelCase__ = False def A ( self : List[Any] , lowercase : Dict=None , lowercase : List[str]=None , lowercase : int=True ) -> Optional[int]: '''simple docstring''' return self.tokenizer.get_decoder_prompt_ids(task=lowercase , language=lowercase , no_timestamps=lowercase ) def __call__( self : Union[str, Any] , *lowercase : str , **lowercase : Union[str, Any] ) -> List[str]: '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*lowercase , **lowercase ) UpperCamelCase__ = kwargs.pop("""audio""" , lowercase ) UpperCamelCase__ = kwargs.pop("""sampling_rate""" , lowercase ) UpperCamelCase__ = kwargs.pop("""text""" , lowercase ) if len(lowercase ) > 0: UpperCamelCase__ = args[0] UpperCamelCase__ = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: UpperCamelCase__ = self.feature_extractor(lowercase , *lowercase , sampling_rate=lowercase , **lowercase ) if text is not None: UpperCamelCase__ = self.tokenizer(lowercase , **lowercase ) if text is None: return inputs elif audio is None: return encodings else: UpperCamelCase__ = encodings["""input_ids"""] return inputs def A ( self : Dict , *lowercase : int , **lowercase : int ) -> int: '''simple docstring''' return self.tokenizer.batch_decode(*lowercase , **lowercase ) def A ( self : str , *lowercase : str , **lowercase : str ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.decode(*lowercase , **lowercase ) def A ( self : Optional[Any] , lowercase : str , lowercase : Dict="np" ) -> Any: '''simple docstring''' return self.tokenizer.get_prompt_ids(lowercase , return_tensors=lowercase )
265
'''simple docstring''' from __future__ import annotations from typing import Any class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , lowercase : int ) -> None: '''simple docstring''' UpperCamelCase__ = num_of_nodes UpperCamelCase__ = [] UpperCamelCase__ = {} def A ( self : Optional[Any] , lowercase : int , lowercase : int , lowercase : int ) -> None: '''simple docstring''' self.m_edges.append([u_node, v_node, weight] ) def A ( self : str , lowercase : int ) -> int: '''simple docstring''' if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def A ( self : Union[str, Any] , lowercase : int ) -> None: '''simple docstring''' if self.m_component[u_node] != u_node: for k in self.m_component: UpperCamelCase__ = self.find_component(lowercase ) def A ( self : Tuple , lowercase : list[int] , lowercase : int , lowercase : int ) -> None: '''simple docstring''' if component_size[u_node] <= component_size[v_node]: UpperCamelCase__ = v_node component_size[v_node] += component_size[u_node] self.set_component(lowercase ) elif component_size[u_node] >= component_size[v_node]: UpperCamelCase__ = self.find_component(lowercase ) component_size[u_node] += component_size[v_node] self.set_component(lowercase ) def A ( self : int ) -> None: '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = 0 UpperCamelCase__ = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) UpperCamelCase__ = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edge UpperCamelCase__ = self.m_component[u] UpperCamelCase__ = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): UpperCamelCase__ = [u, v, w] for edge in minimum_weight_edge: if isinstance(lowercase , lowercase ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edge UpperCamelCase__ = self.m_component[u] UpperCamelCase__ = self.m_component[v] if u_component != v_component: mst_weight += w self.union(lowercase , lowercase , lowercase ) print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n" ) num_of_components -= 1 UpperCamelCase__ = [-1] * self.m_num_of_nodes print(f"The total weight of the minimal spanning tree is: {mst_weight}" ) def __magic_name__( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
265
1
'''simple docstring''' # Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _a : Any = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model _a : Optional[Any] = { # fairseq: 'wmt19-ru-en': {'length_penalty': 1.1}, 'wmt19-en-ru': {'length_penalty': 1.15}, 'wmt19-en-de': {'length_penalty': 1.0}, 'wmt19-de-en': {'length_penalty': 1.1}, # allenai: 'wmt16-en-de-dist-12-1': {'length_penalty': 0.6}, 'wmt16-en-de-dist-6-1': {'length_penalty': 0.6}, 'wmt16-en-de-12-1': {'length_penalty': 0.8}, 'wmt19-de-en-6-6-base': {'length_penalty': 0.6}, 'wmt19-de-en-6-6-big': {'length_penalty': 0.6}, } # this remaps the different models to their organization names _a : str = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: _a : Optional[int] = 'facebook' for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: _a : Optional[int] = 'allenai' def lowerCamelCase__ ( SCREAMING_SNAKE_CASE : List[str] ): UpperCAmelCase = dict((re.sub(R'@@$' , '' , __snake_case ), v) if k.endswith('@@' ) else (re.sub(R'$' , '</w>' , __snake_case ), v) for k, v in d.items() ) UpperCAmelCase = '<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[f'''{k}</w>'''] UpperCAmelCase = d[k] # restore return da def lowerCamelCase__ ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Optional[Any] ): assert os.path.exists(__snake_case ) os.makedirs(__snake_case , exist_ok=__snake_case ) print(f'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models UpperCAmelCase = basename(__snake_case ) UpperCAmelCase = dirname(__snake_case ) UpperCAmelCase = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel UpperCAmelCase = cls.hub_models() UpperCAmelCase = {'bpe': 'fastbpe', 'tokenizer': 'moses'} UpperCAmelCase = '.' # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(f'''using checkpoint {checkpoint_file}''' ) UpperCAmelCase = hub_utils.from_pretrained( __snake_case , __snake_case , __snake_case , archive_map=__snake_case , **__snake_case ) UpperCAmelCase = vars(chkpt['args']['model'] ) UpperCAmelCase = args['source_lang'] UpperCAmelCase = args['target_lang'] UpperCAmelCase = dirname(__snake_case ) UpperCAmelCase = basename(__snake_case ) # dicts UpperCAmelCase = os.path.join(__snake_case , f'''dict.{src_lang}.txt''' ) UpperCAmelCase = os.path.join(__snake_case , f'''dict.{tgt_lang}.txt''' ) UpperCAmelCase = Dictionary.load(__snake_case ) UpperCAmelCase = rewrite_dict_keys(src_dict.indices ) UpperCAmelCase = len(__snake_case ) UpperCAmelCase = os.path.join(__snake_case , 'vocab-src.json' ) print(f'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(__snake_case , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab UpperCAmelCase = True for k in src_vocab.keys(): if not k.islower(): UpperCAmelCase = False break UpperCAmelCase = Dictionary.load(__snake_case ) UpperCAmelCase = rewrite_dict_keys(tgt_dict.indices ) UpperCAmelCase = len(__snake_case ) UpperCAmelCase = os.path.join(__snake_case , 'vocab-tgt.json' ) print(f'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(__snake_case , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # merges_file (bpecodes) UpperCAmelCase = os.path.join(__snake_case , VOCAB_FILES_NAMES['merges_file'] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" UpperCAmelCase = os.path.join(__snake_case , __snake_case ) if os.path.exists(__snake_case ): break with open(__snake_case , encoding='utf-8' ) as fin: UpperCAmelCase = fin.read() UpperCAmelCase = re.sub(R' \d+$' , '' , __snake_case , 0 , re.M ) # remove frequency number print(f'''Generating {merges_file}''' ) with open(__snake_case , 'w' , encoding='utf-8' ) as fout: fout.write(__snake_case ) # model config UpperCAmelCase = os.path.join(__snake_case , 'config.json' ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", f'''need to extend tokenizer to support bpe={args['bpe']}''' assert args["tokenizer"] == "moses", f'''need to extend tokenizer to support bpe={args['tokenizer']}''' UpperCAmelCase = { 'architectures': ['FSMTForConditionalGeneration'], 'model_type': 'fsmt', 'activation_dropout': args['activation_dropout'], 'activation_function': 'relu', 'attention_dropout': args['attention_dropout'], 'd_model': args['decoder_embed_dim'], 'dropout': args['dropout'], 'init_std': 0.02, 'max_position_embeddings': args['max_source_positions'], 'num_hidden_layers': args['encoder_layers'], 'src_vocab_size': src_vocab_size, 'tgt_vocab_size': tgt_vocab_size, 'langs': [src_lang, tgt_lang], 'encoder_attention_heads': args['encoder_attention_heads'], 'encoder_ffn_dim': args['encoder_ffn_embed_dim'], 'encoder_layerdrop': args['encoder_layerdrop'], 'encoder_layers': args['encoder_layers'], 'decoder_attention_heads': args['decoder_attention_heads'], 'decoder_ffn_dim': args['decoder_ffn_embed_dim'], 'decoder_layerdrop': args['decoder_layerdrop'], 'decoder_layers': args['decoder_layers'], 'bos_token_id': 0, 'pad_token_id': 1, 'eos_token_id': 2, 'is_encoder_decoder': True, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_all_embeddings'], } # good hparam defaults to start with UpperCAmelCase = 5 UpperCAmelCase = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: UpperCAmelCase = best_score_hparams[model_dir]['length_penalty'] else: UpperCAmelCase = 1.0 print(f'''Generating {fsmt_model_config_file}''' ) with open(__snake_case , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # tokenizer config UpperCAmelCase = os.path.join(__snake_case , __snake_case ) UpperCAmelCase = { 'langs': [src_lang, tgt_lang], 'model_max_length': 1024, 'do_lower_case': do_lower_case, } print(f'''Generating {fsmt_tokenizer_config_file}''' ) with open(__snake_case , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(__snake_case , ensure_ascii=__snake_case , indent=__snake_case ) ) # model UpperCAmelCase = chkpt['models'][0] UpperCAmelCase = model.state_dict() # rename keys to start with 'model.' UpperCAmelCase = OrderedDict(('model.' + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys UpperCAmelCase = [ 'model.model', 'model.encoder.version', 'model.decoder.version', 'model.encoder_embed_tokens.weight', 'model.decoder_embed_tokens.weight', 'model.encoder.embed_positions._float_tensor', 'model.decoder.embed_positions._float_tensor', ] for k in ignore_keys: model_state_dict.pop(__snake_case , __snake_case ) UpperCAmelCase = FSMTConfig.from_pretrained(__snake_case ) UpperCAmelCase = FSMTForConditionalGeneration(__snake_case ) # check that it loads ok model_new.load_state_dict(__snake_case , strict=__snake_case ) # save UpperCAmelCase = os.path.join(__snake_case , __snake_case ) print(f'''Generating {pytorch_weights_dump_path}''' ) torch.save(__snake_case , __snake_case ) print('Conversion is done!' ) print('\nLast step is to upload the files to s3' ) print(f'''cd {data_root}''' ) print(f'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": _a : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fsmt_checkpoint_path', default=None, type=str, required=True, help=( 'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,' ' bpecodes, etc.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _a : Union[str, Any] = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
447
import argparse import json from tqdm import tqdm def _A ( ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=__snake_case , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=__snake_case , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=__snake_case , help="where to store parsed gold_data_path file" , ) __SCREAMING_SNAKE_CASE = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: __SCREAMING_SNAKE_CASE = json.load(__snake_case ) for dpr_record in tqdm(__snake_case ): __SCREAMING_SNAKE_CASE = dpr_record["question"] __SCREAMING_SNAKE_CASE = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(__snake_case ) + "\n" ) if __name__ == "__main__": main()
693
0
def UpperCamelCase__( UpperCamelCase__ : int , UpperCamelCase__ : int )->Optional[Any]: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
706
# 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__: str = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__: Union[str, Any] = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__: Union[str, Any] = [ '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__: Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
212
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case_ ( __A ): '''simple docstring''' lowerCamelCase = ( "This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image." "It takes two arguments named `image` which should be the original image, and `label` which should be a text " "describing the elements what should be identified in the segmentation mask. The tool returns the mask." ) lowerCamelCase = "CIDAS/clipseg-rd64-refined" lowerCamelCase = "image_segmenter" lowerCamelCase = CLIPSegForImageSegmentation lowerCamelCase = ["image", "text"] lowerCamelCase = ["image"] def __init__( self : Any , *__magic_name__ : Optional[Any] , **__magic_name__ : int ) -> Any: requires_backends(self , ["vision"] ) super().__init__(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : "Image" , __magic_name__ : str ) -> Optional[Any]: return self.pre_processor(text=[label] , images=[image] , padding=__magic_name__ , return_tensors="pt" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int ) -> Tuple: with torch.no_grad(): lowerCamelCase_ : List[str] = self.model(**__magic_name__ ).logits return logits def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[Any] ) -> Any: lowerCamelCase_ : Optional[Any] = outputs.cpu().detach().numpy() lowerCamelCase_ : Tuple = 0 lowerCamelCase_ : Tuple = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
488
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class snake_case_ ( __A ): '''simple docstring''' lowerCamelCase = None lowerCamelCase = None lowerCamelCase = None lowerCamelCase = None class snake_case_ ( __A ): '''simple docstring''' def __init__( self : str , __magic_name__ : Optional[Any]=1 , __magic_name__ : Union[str, Any]=0 , __magic_name__ : List[Any]=2 , __magic_name__ : Optional[Any]=512 , __magic_name__ : Optional[Any]="cls" , __magic_name__ : Any=False , __magic_name__ : Dict=True , **__magic_name__ : Optional[int] , ) -> Union[str, Any]: super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) lowerCamelCase_ : Union[str, Any] = project_dim lowerCamelCase_ : Optional[Any] = pooler_fn lowerCamelCase_ : Optional[int] = learn_encoder lowerCamelCase_ : Any = use_attention_mask class snake_case_ ( __A ): '''simple docstring''' lowerCamelCase = [R"pooler", R"logit_scale"] lowerCamelCase = [R"position_ids", R"predictions.decoder.bias"] lowerCamelCase = "roberta" lowerCamelCase = RobertaSeriesConfig def __init__( self : List[Any] , __magic_name__ : List[str] ) -> Optional[Any]: super().__init__(__magic_name__ ) lowerCamelCase_ : Dict = XLMRobertaModel(__magic_name__ ) lowerCamelCase_ : Optional[int] = nn.Linear(config.hidden_size , config.project_dim ) lowerCamelCase_ : Optional[Any] = getattr(__magic_name__ , "has_pre_transformation" , __magic_name__ ) if self.has_pre_transformation: lowerCamelCase_ : Optional[Any] = nn.Linear(config.hidden_size , config.project_dim ) lowerCamelCase_ : Dict = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[torch.Tensor] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , ) -> Any: lowerCamelCase_ : List[str] = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ : List[Any] = self.base_model( input_ids=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , position_ids=__magic_name__ , head_mask=__magic_name__ , inputs_embeds=__magic_name__ , encoder_hidden_states=__magic_name__ , encoder_attention_mask=__magic_name__ , output_attentions=__magic_name__ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__magic_name__ , ) if self.has_pre_transformation: lowerCamelCase_ : List[Any] = outputs["hidden_states"][-2] lowerCamelCase_ : Any = self.pre_LN(__magic_name__ ) lowerCamelCase_ : str = self.transformation_pre(__magic_name__ ) return TransformationModelOutput( projection_state=__magic_name__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: lowerCamelCase_ : int = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__magic_name__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
488
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase_ = { 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructTextConfig', 'Pix2StructVisionConfig', ], 'processing_pix2struct': ['Pix2StructProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ['Pix2StructImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ 'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Pix2StructPreTrainedModel', 'Pix2StructForConditionalGeneration', 'Pix2StructVisionModel', 'Pix2StructTextModel', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
717
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowerCamelCase__( __lowerCamelCase , __lowerCamelCase): UpperCAmelCase__ : Dict = 1 @register_to_config def __init__( self: List[str] , UpperCamelCase_: int = 10_00 , UpperCamelCase_: Optional[Union[np.ndarray, List[float]]] = None ): # set `betas`, `alphas`, `timesteps` self.set_timesteps(UpperCamelCase_ ) # standard deviation of the initial noise distribution __lowerCamelCase = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. __lowerCamelCase = 4 # running values __lowerCamelCase = [] def lowerCAmelCase__ ( self: Tuple , UpperCamelCase_: int , UpperCamelCase_: Union[str, torch.device] = None ): __lowerCamelCase = num_inference_steps __lowerCamelCase = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] __lowerCamelCase = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: __lowerCamelCase = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: __lowerCamelCase = torch.sin(steps * math.pi / 2 ) ** 2 __lowerCamelCase = (1.0 - self.betas**2) ** 0.5 __lowerCamelCase = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] __lowerCamelCase = timesteps.to(UpperCamelCase_ ) __lowerCamelCase = [] def lowerCAmelCase__ ( self: int , UpperCamelCase_: torch.FloatTensor , UpperCamelCase_: int , UpperCamelCase_: torch.FloatTensor , UpperCamelCase_: bool = True , ): if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) __lowerCamelCase = (self.timesteps == timestep).nonzero().item() __lowerCamelCase = timestep_index + 1 __lowerCamelCase = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(UpperCamelCase_ ) if len(self.ets ) == 1: __lowerCamelCase = self.ets[-1] elif len(self.ets ) == 2: __lowerCamelCase = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: __lowerCamelCase = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: __lowerCamelCase = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) __lowerCamelCase = self._get_prev_sample(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase_ ) def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: torch.FloatTensor , *UpperCamelCase_: Dict , **UpperCamelCase_: Union[str, Any] ): return sample def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Any , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Any ): __lowerCamelCase = self.alphas[timestep_index] __lowerCamelCase = self.betas[timestep_index] __lowerCamelCase = self.alphas[prev_timestep_index] __lowerCamelCase = self.betas[prev_timestep_index] __lowerCamelCase = (sample - sigma * ets) / max(UpperCamelCase_ , 1E-8 ) __lowerCamelCase = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self: List[Any] ): return self.config.num_train_timesteps
80
0
'''simple docstring''' def _UpperCamelCase ( ): UpperCAmelCase__ : int = [] UpperCAmelCase__ : str = 1 while len(UpperCamelCase__ ) < 1e6: constant.append(str(UpperCamelCase__ ) ) i += 1 UpperCAmelCase__ : Optional[Any] = """""".join(UpperCamelCase__ ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[9_9] ) * int(constant[9_9_9] ) * int(constant[9_9_9_9] ) * int(constant[9_9_9_9_9] ) * int(constant[9_9_9_9_9_9] ) ) if __name__ == "__main__": print(solution())
407
'''simple docstring''' 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 DeformableDetrImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , _lowerCamelCase , _lowerCamelCase=7 , _lowerCamelCase=3 , _lowerCamelCase=30 , _lowerCamelCase=400 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=[0.5, 0.5, 0.5] , _lowerCamelCase=[0.5, 0.5, 0.5] , _lowerCamelCase=True , _lowerCamelCase=1 / 255 , _lowerCamelCase=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p UpperCAmelCase__ : List[str] = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333} UpperCAmelCase__ : List[Any] = parent UpperCAmelCase__ : str = batch_size UpperCAmelCase__ : List[Any] = num_channels UpperCAmelCase__ : List[str] = min_resolution UpperCAmelCase__ : Optional[Any] = max_resolution UpperCAmelCase__ : List[str] = do_resize UpperCAmelCase__ : Optional[int] = size UpperCAmelCase__ : Dict = do_normalize UpperCAmelCase__ : int = image_mean UpperCAmelCase__ : Dict = image_std UpperCAmelCase__ : Any = do_rescale UpperCAmelCase__ : str = rescale_factor UpperCAmelCase__ : List[str] = do_pad def snake_case__ ( self): 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 snake_case__ ( self , _lowerCamelCase , _lowerCamelCase=False): if not batched: UpperCAmelCase__ : List[Any] = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image): UpperCAmelCase__ , UpperCAmelCase__ : str = image.size else: UpperCAmelCase__ , UpperCAmelCase__ : List[str] = image.shape[1], image.shape[2] if w < h: UpperCAmelCase__ : List[Any] = int(self.size["""shortest_edge"""] * h / w) UpperCAmelCase__ : List[str] = self.size["""shortest_edge"""] elif w > h: UpperCAmelCase__ : List[str] = self.size["""shortest_edge"""] UpperCAmelCase__ : Optional[int] = int(self.size["""shortest_edge"""] * w / h) else: UpperCAmelCase__ : List[str] = self.size["""shortest_edge"""] UpperCAmelCase__ : int = self.size["""shortest_edge"""] else: UpperCAmelCase__ : str = [] for image in image_inputs: UpperCAmelCase__ , UpperCAmelCase__ : Any = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) UpperCAmelCase__ : Any = max(_lowerCamelCase , key=lambda _lowerCamelCase: item[0])[0] UpperCAmelCase__ : List[Any] = max(_lowerCamelCase , key=lambda _lowerCamelCase: item[1])[1] return expected_height, expected_width @require_torch @require_vision class _snake_case ( a__ , unittest.TestCase ): lowerCAmelCase :Union[str, Any] = DeformableDetrImageProcessor if is_vision_available() else None def snake_case__ ( self): UpperCAmelCase__ : Optional[Any] = DeformableDetrImageProcessingTester(self) @property def snake_case__ ( self): return self.image_processor_tester.prepare_image_processor_dict() def snake_case__ ( self): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(_lowerCamelCase , """image_mean""")) self.assertTrue(hasattr(_lowerCamelCase , """image_std""")) self.assertTrue(hasattr(_lowerCamelCase , """do_normalize""")) self.assertTrue(hasattr(_lowerCamelCase , """do_resize""")) self.assertTrue(hasattr(_lowerCamelCase , """do_rescale""")) self.assertTrue(hasattr(_lowerCamelCase , """do_pad""")) self.assertTrue(hasattr(_lowerCamelCase , """size""")) def snake_case__ ( self): UpperCAmelCase__ : int = 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 , _lowerCamelCase) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_lowerCamelCase) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84}) self.assertEqual(image_processor.do_pad , _lowerCamelCase) def snake_case__ ( self): pass def snake_case__ ( self): # Initialize image_processing UpperCAmelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict) # create random PIL images UpperCAmelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image) # Test not batched input UpperCAmelCase__ : Dict = image_processing(image_inputs[0] , return_tensors="""pt""").pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.image_processor_tester.get_expected_values(_lowerCamelCase) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ , UpperCAmelCase__ : int = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase) UpperCAmelCase__ : Optional[int] = image_processing(_lowerCamelCase , 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 snake_case__ ( self): # Initialize image_processing UpperCAmelCase__ : int = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors UpperCAmelCase__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray) # Test not batched input UpperCAmelCase__ : int = image_processing(image_inputs[0] , return_tensors="""pt""").pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : Optional[Any] = image_processing(_lowerCamelCase , return_tensors="""pt""").pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def snake_case__ ( self): # Initialize image_processing UpperCAmelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors UpperCAmelCase__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor) # Test not batched input UpperCAmelCase__ : Dict = image_processing(image_inputs[0] , return_tensors="""pt""").pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : int = image_processing(_lowerCamelCase , return_tensors="""pt""").pixel_values UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def snake_case__ ( self): # prepare image and target UpperCAmelCase__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""") with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""") as f: UpperCAmelCase__ : Dict = json.loads(f.read()) UpperCAmelCase__ : int = {"""image_id""": 3_9769, """annotations""": target} # encode them UpperCAmelCase__ : Dict = DeformableDetrImageProcessor() UpperCAmelCase__ : int = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors="""pt""") # verify pixel values UpperCAmelCase__ : Tuple = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding["""pixel_values"""].shape , _lowerCamelCase) UpperCAmelCase__ : Any = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4)) # verify area UpperCAmelCase__ : List[Any] = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowerCamelCase)) # verify boxes UpperCAmelCase__ : Union[str, Any] = torch.Size([6, 4]) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowerCamelCase) UpperCAmelCase__ : Dict = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowerCamelCase , atol=1e-3)) # verify image_id UpperCAmelCase__ : Optional[int] = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowerCamelCase)) # verify is_crowd UpperCAmelCase__ : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowerCamelCase)) # verify class_labels UpperCAmelCase__ : Any = torch.tensor([75, 75, 63, 65, 17, 17]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowerCamelCase)) # verify orig_size UpperCAmelCase__ : int = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowerCamelCase)) # verify size UpperCAmelCase__ : List[Any] = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowerCamelCase)) @slow def snake_case__ ( self): # prepare image, target and masks_path UpperCAmelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""") with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""") as f: UpperCAmelCase__ : Optional[int] = json.loads(f.read()) UpperCAmelCase__ : Optional[Any] = {"""file_name""": """000000039769.png""", """image_id""": 3_9769, """segments_info""": target} UpperCAmelCase__ : Tuple = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""") # encode them UpperCAmelCase__ : List[str] = DeformableDetrImageProcessor(format="""coco_panoptic""") UpperCAmelCase__ : Tuple = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors="""pt""") # verify pixel values UpperCAmelCase__ : str = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding["""pixel_values"""].shape , _lowerCamelCase) UpperCAmelCase__ : Union[str, Any] = torch.tensor([0.2796, 0.3138, 0.3481]) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4)) # verify area UpperCAmelCase__ : str = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowerCamelCase)) # verify boxes UpperCAmelCase__ : List[str] = torch.Size([6, 4]) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowerCamelCase) UpperCAmelCase__ : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowerCamelCase , atol=1e-3)) # verify image_id UpperCAmelCase__ : Tuple = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowerCamelCase)) # verify is_crowd UpperCAmelCase__ : List[str] = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowerCamelCase)) # verify class_labels UpperCAmelCase__ : List[Any] = torch.tensor([17, 17, 63, 75, 75, 93]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowerCamelCase)) # verify masks UpperCAmelCase__ : Dict = 82_2873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , _lowerCamelCase) # verify orig_size UpperCAmelCase__ : Any = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowerCamelCase)) # verify size UpperCAmelCase__ : int = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowerCamelCase))
407
1
'''simple docstring''' import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : int = 16 __A : Optional[int] = 32 def UpperCamelCase_ ( A__ : Optional[Any] , A__ : int = 16 ): '''simple docstring''' lowerCAmelCase_ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) lowerCAmelCase_ : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(A__ : str ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase_ : str = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCAmelCase_ : Dict = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase_ : Tuple = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(A__ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCAmelCase_ : Any = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCAmelCase_ : str = 16 elif accelerator.mixed_precision != "no": lowerCAmelCase_ : Any = 8 else: lowerCAmelCase_ : Optional[Any] = None return tokenizer.pad( _SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. lowerCAmelCase_ : Union[str, Any] = DataLoader( tokenized_datasets["""train"""] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) lowerCAmelCase_ : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : Any = mocked_dataloaders # noqa: F811 def UpperCamelCase_ ( A__ : List[Any] , A__ : List[Any] ): '''simple docstring''' if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , _SCREAMING_SNAKE_CASE ) == "1": lowerCAmelCase_ : List[Any] = 2 # Initialize accelerator lowerCAmelCase_ : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase_ : List[Any] = config["""lr"""] lowerCAmelCase_ : Any = int(config["""num_epochs"""] ) lowerCAmelCase_ : List[Any] = int(config["""seed"""] ) lowerCAmelCase_ : Optional[int] = int(config["""batch_size"""] ) lowerCAmelCase_ : Tuple = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=_SCREAMING_SNAKE_CASE ) def inner_training_loop(A__ : List[Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(_SCREAMING_SNAKE_CASE ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase_ : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=_SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCAmelCase_ : Dict = model.to(accelerator.device ) # Instantiate optimizer lowerCAmelCase_ : Optional[int] = AdamW(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) lowerCAmelCase_, lowerCAmelCase_ : Optional[Any] = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Instantiate scheduler lowerCAmelCase_ : Tuple = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=1_00 , num_training_steps=(len(_SCREAMING_SNAKE_CASE ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ : Optional[Any] = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(_SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowerCAmelCase_ : Dict = model(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase_ : Optional[Any] = outputs.loss accelerator.backward(_SCREAMING_SNAKE_CASE ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase_ : Tuple = model(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase_ : Dict = outputs.logits.argmax(dim=-1 ) lowerCAmelCase_, lowerCAmelCase_ : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase_ : Dict = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' , _SCREAMING_SNAKE_CASE ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCamelCase_ ( ): '''simple docstring''' lowerCAmelCase_ : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) lowerCAmelCase_ : Dict = parser.parse_args() lowerCAmelCase_ : Any = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
701
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename __A : Dict = "http://www.mocksite.com/file1.txt" __A : List[str] = "\"text\": [\"foo\", \"foo\"]" __A : int = "6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8" class __snake_case : """simple docstring""" lowercase = 2_00 lowercase = {'Content-Length': '100'} lowercase = {} def __lowercase ( self : Union[str, Any] , **lowerCamelCase : Optional[int] ) -> str: return [bytes(lowerCamelCase , """utf-8""" )] def UpperCamelCase_ ( *A__ : List[str] , **A__ : Union[str, Any] ): '''simple docstring''' return MockResponse() @pytest.mark.parametrize("""urls_type""" , [str, list, dict] ) def UpperCamelCase_ ( A__ : List[Any] , A__ : List[Any] , A__ : str ): '''simple docstring''' import requests monkeypatch.setattr(A__ , """request""" , A__ ) lowerCAmelCase_ : Tuple = URL if issubclass(A__ , A__ ): lowerCAmelCase_ : Optional[Any] = url elif issubclass(A__ , A__ ): lowerCAmelCase_ : Dict = [url] elif issubclass(A__ , A__ ): lowerCAmelCase_ : Tuple = {"""train""": url} lowerCAmelCase_ : List[Any] = """dummy""" lowerCAmelCase_ : str = """downloads""" lowerCAmelCase_ : Dict = tmp_path lowerCAmelCase_ : Any = DownloadConfig( cache_dir=os.path.join(A__ , A__ ) , use_etag=A__ , ) lowerCAmelCase_ : List[Any] = DownloadManager(dataset_name=A__ , download_config=A__ ) lowerCAmelCase_ : int = dl_manager.download(A__ ) lowerCAmelCase_ : Any = urls for downloaded_paths in [downloaded_paths]: if isinstance(A__ , A__ ): lowerCAmelCase_ : str = [downloaded_paths] lowerCAmelCase_ : Any = [urls] elif isinstance(A__ , A__ ): assert "train" in downloaded_paths.keys() lowerCAmelCase_ : Union[str, Any] = downloaded_paths.values() lowerCAmelCase_ : Optional[Any] = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(A__ , A__ ): assert downloaded_path == dl_manager.downloaded_paths[input_url] lowerCAmelCase_ : Tuple = Path(A__ ) lowerCAmelCase_ : List[Any] = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() lowerCAmelCase_ : Optional[Any] = downloaded_path.read_text() assert content == CONTENT lowerCAmelCase_ : Tuple = downloaded_path.with_suffix(""".json""" ) assert metadata_downloaded_path.exists() lowerCAmelCase_ : Tuple = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize("""paths_type""" , [str, list, dict] ) def UpperCamelCase_ ( A__ : Union[str, Any] , A__ : List[Any] , A__ : List[str] ): '''simple docstring''' lowerCAmelCase_ : int = str(A__ ) if issubclass(A__ , A__ ): lowerCAmelCase_ : int = filename elif issubclass(A__ , A__ ): lowerCAmelCase_ : List[str] = [filename] elif issubclass(A__ , A__ ): lowerCAmelCase_ : Union[str, Any] = {"""train""": filename} lowerCAmelCase_ : Optional[int] = """dummy""" lowerCAmelCase_ : str = xz_file.parent lowerCAmelCase_ : List[str] = """extracted""" lowerCAmelCase_ : Union[str, Any] = DownloadConfig( cache_dir=A__ , use_etag=A__ , ) lowerCAmelCase_ : str = DownloadManager(dataset_name=A__ , download_config=A__ ) lowerCAmelCase_ : Union[str, Any] = dl_manager.extract(A__ ) lowerCAmelCase_ : List[Any] = paths for extracted_paths in [extracted_paths]: if isinstance(A__ , A__ ): lowerCAmelCase_ : List[str] = [extracted_paths] lowerCAmelCase_ : Union[str, Any] = [paths] elif isinstance(A__ , A__ ): assert "train" in extracted_paths.keys() lowerCAmelCase_ : Union[str, Any] = extracted_paths.values() lowerCAmelCase_ : int = paths.values() assert extracted_paths for extracted_path, input_path in zip(A__ , A__ ): assert extracted_path == dl_manager.extracted_paths[input_path] lowerCAmelCase_ : int = Path(A__ ) lowerCAmelCase_ : Optional[Any] = extracted_path.parts assert parts[-1] == hash_url_to_filename(A__ , etag=A__ ) assert parts[-2] == extracted_subdir assert extracted_path.exists() lowerCAmelCase_ : Any = extracted_path.read_text() lowerCAmelCase_ : Optional[Any] = text_file.read_text() assert extracted_file_content == expected_file_content def UpperCamelCase_ ( A__ : Dict , A__ : Any ): '''simple docstring''' assert path.endswith(""".jsonl""" ) for num_items, line in enumerate(A__ , start=1 ): lowerCAmelCase_ : int = json.loads(line.decode("""utf-8""" ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("""archive_jsonl""" , ["""tar_jsonl_path""", """zip_jsonl_path"""] ) def UpperCamelCase_ ( A__ : Optional[Any] , A__ : List[Any] ): '''simple docstring''' lowerCAmelCase_ : List[str] = request.getfixturevalue(A__ ) lowerCAmelCase_ : List[Any] = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(A__ ) , start=1 ): _test_jsonl(A__ , A__ ) assert num_jsonl == 2 @pytest.mark.parametrize("""archive_nested_jsonl""" , ["""tar_nested_jsonl_path""", """zip_nested_jsonl_path"""] ) def UpperCamelCase_ ( A__ : str , A__ : int ): '''simple docstring''' lowerCAmelCase_ : Tuple = request.getfixturevalue(A__ ) lowerCAmelCase_ : str = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(A__ ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(A__ ) , start=1 ): _test_jsonl(A__ , A__ ) assert num_tar == 1 assert num_jsonl == 2 def UpperCamelCase_ ( A__ : Tuple ): '''simple docstring''' lowerCAmelCase_ : Optional[Any] = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(A__ ) , start=1 ): assert os.path.basename(A__ ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
398
0
import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py lowerCAmelCase_ = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase_ = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. lowerCAmelCase_ = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") lowerCAmelCase_ = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. lowerCAmelCase_ = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Fill this with tuples (pipeline_tag, model_mapping, auto_model) lowerCAmelCase_ = [ ("""pretraining""", """MODEL_FOR_PRETRAINING_MAPPING_NAMES""", """AutoModelForPreTraining"""), ("""feature-extraction""", """MODEL_MAPPING_NAMES""", """AutoModel"""), ("""audio-classification""", """MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioClassification"""), ("""text-generation""", """MODEL_FOR_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForCausalLM"""), ("""automatic-speech-recognition""", """MODEL_FOR_CTC_MAPPING_NAMES""", """AutoModelForCTC"""), ("""image-classification""", """MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForImageClassification"""), ("""image-segmentation""", """MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES""", """AutoModelForImageSegmentation"""), ("""fill-mask""", """MODEL_FOR_MASKED_LM_MAPPING_NAMES""", """AutoModelForMaskedLM"""), ("""object-detection""", """MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForObjectDetection"""), ( """zero-shot-object-detection""", """MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForZeroShotObjectDetection""", ), ("""question-answering""", """MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForQuestionAnswering"""), ("""text2text-generation""", """MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForSeq2SeqLM"""), ("""text-classification""", """MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForSequenceClassification"""), ("""automatic-speech-recognition""", """MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES""", """AutoModelForSpeechSeq2Seq"""), ( """table-question-answering""", """MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForTableQuestionAnswering""", ), ("""token-classification""", """MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForTokenClassification"""), ("""multiple-choice""", """MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES""", """AutoModelForMultipleChoice"""), ( """next-sentence-prediction""", """MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES""", """AutoModelForNextSentencePrediction""", ), ( """audio-frame-classification""", """MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioFrameClassification""", ), ("""audio-xvector""", """MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES""", """AutoModelForAudioXVector"""), ( """document-question-answering""", """MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForDocumentQuestionAnswering""", ), ( """visual-question-answering""", """MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForVisualQuestionAnswering""", ), ("""image-to-text""", """MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES""", """AutoModelForVision2Seq"""), ( """zero-shot-image-classification""", """MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForZeroShotImageClassification""", ), ("""depth-estimation""", """MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES""", """AutoModelForDepthEstimation"""), ("""video-classification""", """MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForVideoClassification"""), ("""mask-generation""", """MODEL_FOR_MASK_GENERATION_MAPPING_NAMES""", """AutoModelForMaskGeneration"""), ] def lowerCamelCase_ ( lowerCAmelCase: Any )-> List[Any]: _snake_case : str = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , lowerCAmelCase ) return [m.group(0 ) for m in matches] def lowerCamelCase_ ( )-> List[Any]: _snake_case : int = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _snake_case : List[str] = { config.replace('Config' , '' ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _snake_case : int = collections.defaultdict(lowerCAmelCase ) _snake_case : Optional[Any] = collections.defaultdict(lowerCAmelCase ) _snake_case : Any = collections.defaultdict(lowerCAmelCase ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(lowerCAmelCase ): _snake_case : Any = None if _re_tf_models.match(lowerCAmelCase ) is not None: _snake_case : Optional[Any] = tf_models _snake_case : List[str] = _re_tf_models.match(lowerCAmelCase ).groups()[0] elif _re_flax_models.match(lowerCAmelCase ) is not None: _snake_case : Tuple = flax_models _snake_case : List[Any] = _re_flax_models.match(lowerCAmelCase ).groups()[0] elif _re_pt_models.match(lowerCAmelCase ) is not None: _snake_case : Optional[int] = pt_models _snake_case : str = _re_pt_models.match(lowerCAmelCase ).groups()[0] if lookup_dict is not None: while len(lowerCAmelCase ) > 0: if attr_name in model_prefix_to_model_type: _snake_case : Optional[int] = True break # Try again after removing the last word in the name _snake_case : Optional[int] = ''.join(camel_case_split(lowerCAmelCase )[:-1] ) _snake_case : List[str] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _snake_case : Tuple = list(lowerCAmelCase ) all_models.sort() _snake_case : Dict = {'model_type': all_models} _snake_case : Any = [pt_models[t] for t in all_models] _snake_case : Dict = [tf_models[t] for t in all_models] _snake_case : Tuple = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _snake_case : Union[str, Any] = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _snake_case : Dict = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _snake_case : str = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _snake_case : Union[str, Any] = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _snake_case : int = 'AutoTokenizer' _snake_case : Union[str, Any] = [processors[t] for t in all_models] return pd.DataFrame(lowerCAmelCase ) def lowerCamelCase_ ( lowerCAmelCase: List[Any] )-> List[Any]: _snake_case : Tuple = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _snake_case : int = [model_mapping, F"""TF_{model_mapping}""", F"""FLAX_{model_mapping}"""] _snake_case : List[str] = [auto_class, F"""TF_{auto_class}""", F"""Flax_{auto_class}"""] # Loop through all three frameworks for module, cls, mapping in zip(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): # The type of pipeline may not exist in this framework if not hasattr(lowerCAmelCase , lowerCAmelCase ): continue # First extract all model_names _snake_case : str = [] for name in getattr(lowerCAmelCase , lowerCAmelCase ).values(): if isinstance(lowerCAmelCase , lowerCAmelCase ): model_names.append(lowerCAmelCase ) else: model_names.extend(list(lowerCAmelCase ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def lowerCamelCase_ ( lowerCAmelCase: Dict , lowerCAmelCase: Tuple )-> Tuple: _snake_case : Union[str, Any] = get_frameworks_table() _snake_case : Union[str, Any] = Dataset.from_pandas(lowerCAmelCase ) _snake_case : List[Any] = hf_hub_download( 'huggingface/transformers-metadata' , 'pipeline_tags.json' , repo_type='dataset' , token=lowerCAmelCase ) _snake_case : Optional[int] = Dataset.from_json(lowerCAmelCase ) _snake_case : Any = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(lowerCAmelCase ) ) } _snake_case : Optional[int] = update_pipeline_and_auto_class_table(lowerCAmelCase ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _snake_case : Optional[int] = sorted(table.keys() ) _snake_case : Dict = pd.DataFrame( { 'model_class': model_classes, 'pipeline_tag': [table[m][0] for m in model_classes], 'auto_class': [table[m][1] for m in model_classes], } ) _snake_case : Any = Dataset.from_pandas(lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(lowerCAmelCase , 'frameworks.json' ) ) tags_dataset.to_json(os.path.join(lowerCAmelCase , 'pipeline_tags.json' ) ) if commit_sha is not None: _snake_case : List[str] = ( F"""Update with commit {commit_sha}\n\nSee: """ F"""https://github.com/huggingface/transformers/commit/{commit_sha}""" ) else: _snake_case : Tuple = 'Update' upload_folder( repo_id='huggingface/transformers-metadata' , folder_path=lowerCAmelCase , repo_type='dataset' , token=lowerCAmelCase , commit_message=lowerCAmelCase , ) def lowerCamelCase_ ( )-> Optional[int]: _snake_case : Dict = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _snake_case : Union[str, Any] = transformers_module.pipelines.SUPPORTED_TASKS _snake_case : Tuple = [] for key in pipeline_tasks: if key not in in_table: _snake_case : Dict = pipeline_tasks[key]['pt'] if isinstance(lowerCAmelCase , (list, tuple) ): _snake_case : Tuple = model[0] _snake_case : List[Any] = model.__name__ if model not in in_table.values(): missing.append(lowerCAmelCase ) if len(lowerCAmelCase ) > 0: _snake_case : Dict = ', '.join(lowerCAmelCase ) raise ValueError( 'The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside ' F"""`utils/update_metadata.py`: {msg}. Please add them!""" ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument("""--token""", type=str, help="""The token to use to push to the transformers-metadata dataset.""") parser.add_argument("""--commit_sha""", type=str, help="""The sha of the commit going with this update.""") parser.add_argument("""--check-only""", action="""store_true""", help="""Activate to just check all pipelines are present.""") lowerCAmelCase_ = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
411
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { """tiiuae/falcon-40b""": """https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json""", """tiiuae/falcon-7b""": """https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json""", } class _lowerCAmelCase ( UpperCAmelCase_ ): '''simple docstring''' a_ : List[str] ="""falcon""" a_ : List[Any] =["""past_key_values"""] def __init__( self : Dict , UpperCamelCase : List[Any]=6_50_24 , UpperCamelCase : Dict=45_44 , UpperCamelCase : Optional[Any]=32 , UpperCamelCase : Optional[int]=71 , UpperCamelCase : Any=1e-5 , UpperCamelCase : List[str]=0.02 , UpperCamelCase : Optional[Any]=True , UpperCamelCase : Optional[Any]=0.0 , UpperCamelCase : Any=0.0 , UpperCamelCase : Union[str, Any]=None , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : Dict=False , UpperCamelCase : Dict=True , UpperCamelCase : List[Any]=True , UpperCamelCase : str=False , UpperCamelCase : Dict=11 , UpperCamelCase : Dict=11 , **UpperCamelCase : Optional[int] , ): '''simple docstring''' _snake_case : Optional[Any] = vocab_size # Backward compatibility with n_embed kwarg _snake_case : Optional[Any] = kwargs.pop('n_embed' , UpperCamelCase ) _snake_case : Dict = hidden_size if n_embed is None else n_embed _snake_case : Dict = num_hidden_layers _snake_case : Dict = num_attention_heads _snake_case : List[str] = layer_norm_epsilon _snake_case : Optional[int] = initializer_range _snake_case : str = use_cache _snake_case : str = hidden_dropout _snake_case : str = attention_dropout _snake_case : List[Any] = bos_token_id _snake_case : Union[str, Any] = eos_token_id _snake_case : Tuple = num_attention_heads if num_kv_heads is None else num_kv_heads _snake_case : Union[str, Any] = alibi _snake_case : Optional[int] = new_decoder_architecture _snake_case : List[Any] = multi_query # Ignored when new_decoder_architecture is True _snake_case : Dict = parallel_attn _snake_case : Dict = bias super().__init__(bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return self.hidden_size // self.num_attention_heads @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return not self.alibi
411
1
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__ : Tuple =logging.get_logger(__name__) if is_vision_available(): import PIL class __A ( _SCREAMING_SNAKE_CASE ): lowerCamelCase =['''pixel_values'''] def __init__( self : Union[str, Any] , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 2_55 , lowerCamelCase : bool = True , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : bool = True , **lowerCamelCase : str , ): """simple docstring""" super().__init__(**lowerCamelCase ) __A : str = size if size is not None else {"""shortest_edge""": 2_24} __A : Tuple = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __A : Optional[Any] = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} __A : Union[str, Any] = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="""crop_size""" ) __A : List[Any] = do_resize __A : int = size __A : int = resample __A : Dict = do_center_crop __A : int = crop_size __A : Optional[int] = do_rescale __A : Union[str, Any] = rescale_factor __A : Tuple = do_normalize __A : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __A : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD __A : int = do_convert_rgb def lowercase_( self : Tuple , lowerCamelCase : np.ndarray , lowerCamelCase : Dict[str, int] , lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Dict , ): """simple docstring""" __A : Dict = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) __A : int = get_resize_output_image_size(lowerCamelCase , size=size["""shortest_edge"""] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowercase_( self : Tuple , lowerCamelCase : np.ndarray , lowerCamelCase : Dict[str, int] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Union[str, Any] , ): """simple docstring""" __A : str = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["""height"""], size["""width"""]) , data_format=lowerCamelCase , **lowerCamelCase ) def lowercase_( self : int , lowerCamelCase : np.ndarray , lowerCamelCase : Union[int, float] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : int , ): """simple docstring""" return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowercase_( self : Optional[Any] , lowerCamelCase : np.ndarray , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Union[float, List[float]] , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : List[Any] , ): """simple docstring""" return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def lowercase_( self : List[str] , lowerCamelCase : ImageInput , lowerCamelCase : bool = None , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : PILImageResampling = None , lowerCamelCase : bool = None , lowerCamelCase : int = None , lowerCamelCase : bool = None , lowerCamelCase : float = None , lowerCamelCase : bool = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : Optional[Union[float, List[float]]] = None , lowerCamelCase : bool = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase : List[str] , ): """simple docstring""" __A : List[Any] = do_resize if do_resize is not None else self.do_resize __A : Dict = size if size is not None else self.size __A : List[str] = get_size_dict(lowerCamelCase , param_name="""size""" , default_to_square=lowerCamelCase ) __A : Optional[Any] = resample if resample is not None else self.resample __A : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __A : Tuple = crop_size if crop_size is not None else self.crop_size __A : Tuple = get_size_dict(lowerCamelCase , param_name="""crop_size""" , default_to_square=lowerCamelCase ) __A : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __A : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor __A : Tuple = do_normalize if do_normalize is not None else self.do_normalize __A : int = image_mean if image_mean is not None else self.image_mean __A : Any = image_std if image_std is not None else self.image_std __A : Union[str, Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __A : Optional[int] = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: 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: __A : Dict = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __A : List[str] = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __A : Dict = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: __A : int = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: __A : List[str] = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: __A : Any = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] __A : Union[str, Any] = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __A : Any = {"""pixel_values""": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
721
'''simple docstring''' def A_ ( __SCREAMING_SNAKE_CASE : Dict ) -> Optional[Any]: """simple docstring""" if not head: return True # split the list to two parts __A , __A : Any = head.next, head while fast and fast.next: __A : List[str] = fast.next.next __A : List[Any] = slow.next __A : int = slow.next __A : List[str] = None # Don't forget here! But forget still works! # reverse the second part __A : Dict = None while second: __A : Dict = second.next __A : str = node __A : int = second __A : Optional[int] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False __A : List[Any] = node.next __A : Tuple = head.next return True def A_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[int]: """simple docstring""" if not head or not head.next: return True # 1. Get the midpoint (slow) __A : int = head while fast and fast.next: __A , __A : Optional[int] = fast.next.next, slow.next # 2. Push the second half into the stack __A : Union[str, Any] = [slow.val] while slow.next: __A : List[str] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False __A : Tuple = cur.next return True def A_ ( __SCREAMING_SNAKE_CASE : Dict ) -> Any: """simple docstring""" if not head or not head.next: return True __A : List[Any] = {} __A : Optional[int] = 0 while head: if head.val in d: d[head.val].append(__SCREAMING_SNAKE_CASE ) else: __A : Tuple = [pos] __A : List[Any] = head.next pos += 1 __A : List[Any] = pos - 1 __A : List[str] = 0 for v in d.values(): if len(__SCREAMING_SNAKE_CASE ) % 2 != 0: middle += 1 else: __A : List[Any] = 0 for i in range(0 , len(__SCREAMING_SNAKE_CASE ) ): if v[i] + v[len(__SCREAMING_SNAKE_CASE ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
499
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : int = { """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json""", } class __UpperCamelCase ( _lowerCAmelCase ): __snake_case :Union[str, Any] = 'lxmert' __snake_case :Union[str, Any] = {} def __init__( self : List[str] , _lowerCAmelCase : Dict=3_0522 , _lowerCAmelCase : List[str]=768 , _lowerCAmelCase : Union[str, Any]=12 , _lowerCAmelCase : Union[str, Any]=9500 , _lowerCAmelCase : Union[str, Any]=1600 , _lowerCAmelCase : Optional[Any]=400 , _lowerCAmelCase : Tuple=3072 , _lowerCAmelCase : List[Any]="gelu" , _lowerCAmelCase : int=0.1 , _lowerCAmelCase : Dict=0.1 , _lowerCAmelCase : Tuple=512 , _lowerCAmelCase : Tuple=2 , _lowerCAmelCase : Optional[Any]=0.02 , _lowerCAmelCase : List[str]=1e-12 , _lowerCAmelCase : Any=9 , _lowerCAmelCase : Optional[Any]=5 , _lowerCAmelCase : Any=5 , _lowerCAmelCase : Dict=2048 , _lowerCAmelCase : int=4 , _lowerCAmelCase : Optional[Any]=6.67 , _lowerCAmelCase : Optional[Any]=True , _lowerCAmelCase : int=True , _lowerCAmelCase : int=True , _lowerCAmelCase : str=True , _lowerCAmelCase : Dict=True , _lowerCAmelCase : int=True , _lowerCAmelCase : int=True , **_lowerCAmelCase : Tuple , ) -> Dict: """simple docstring""" __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_attention_heads __lowercase = hidden_act __lowercase = intermediate_size __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = num_qa_labels __lowercase = num_object_labels __lowercase = num_attr_labels __lowercase = l_layers __lowercase = x_layers __lowercase = r_layers __lowercase = visual_feat_dim __lowercase = visual_pos_dim __lowercase = visual_loss_normalizer __lowercase = task_matched __lowercase = task_mask_lm __lowercase = task_obj_predict __lowercase = task_qa __lowercase = visual_obj_loss __lowercase = visual_attr_loss __lowercase = visual_feat_loss __lowercase = {"""vision""": r_layers, """cross_encoder""": x_layers, """language""": l_layers} super().__init__(**_lowerCAmelCase )
80
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor _lowercase = logging.get_logger(__name__) class a_ ( UpperCAmelCase__ ): def __init__( self : Tuple , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : List[str] ): warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' , __lowerCAmelCase , ) super().__init__(*__lowerCAmelCase , **__lowerCAmelCase )
356
0
'''simple docstring''' import itertools import math def __magic_name__( _A ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __magic_name__( ): '''simple docstring''' UpperCamelCase__ = 2 while True: if is_prime(_A ): yield num num += 1 def __magic_name__( _A = 1_0001 ): '''simple docstring''' return next(itertools.islice(prime_generator() , nth - 1 , _A ) ) if __name__ == "__main__": print(f"""{solution() = }""")
718
'''simple docstring''' import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib lowerCamelCase_ : Any = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } lowerCamelCase_ : Optional[int] = logging.WARNING def __magic_name__( ): '''simple docstring''' UpperCamelCase__ = os.getenv("""DATASETS_VERBOSITY""" , _A ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"Unknown option DATASETS_VERBOSITY={env_level_str}, " f"has to be one of: { ', '.join(log_levels.keys() ) }" ) return _default_log_level def __magic_name__( ): '''simple docstring''' return __name__.split(""".""" )[0] def __magic_name__( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def __magic_name__( ): '''simple docstring''' UpperCamelCase__ = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def __magic_name__( ): '''simple docstring''' UpperCamelCase__ = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def __magic_name__( _A = None ): '''simple docstring''' if name is None: UpperCamelCase__ = _get_library_name() return logging.getLogger(_A ) def __magic_name__( ): '''simple docstring''' return _get_library_root_logger().getEffectiveLevel() def __magic_name__( _A ): '''simple docstring''' _get_library_root_logger().setLevel(_A ) def __magic_name__( ): '''simple docstring''' return set_verbosity(_A ) def __magic_name__( ): '''simple docstring''' return set_verbosity(_A ) def __magic_name__( ): '''simple docstring''' return set_verbosity(_A ) def __magic_name__( ): '''simple docstring''' return set_verbosity(_A ) def __magic_name__( ): '''simple docstring''' UpperCamelCase__ = False def __magic_name__( ): '''simple docstring''' UpperCamelCase__ = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : int , *lowercase : Any , **lowercase : int ) -> List[Any]: # pylint: disable=unused-argument '''simple docstring''' UpperCamelCase__ = args[0] if args else None def __iter__( self : str ) -> List[str]: '''simple docstring''' return iter(self._iterator ) def __getattr__( self : Optional[int] , lowercase : Tuple ) -> int: '''simple docstring''' def empty_fn(*lowercase : List[Any] , **lowercase : Dict ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Dict ) -> Tuple: '''simple docstring''' return self def __exit__( self : Tuple , lowercase : Optional[Any] , lowercase : Any , lowercase : int ) -> Any: '''simple docstring''' return lowerCamelCase_ : str = True class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __call__( self : List[Any] , *lowercase : str , lowercase : Optional[int]=False , **lowercase : Optional[int] ) -> Optional[int]: '''simple docstring''' if _tqdm_active and not disable: return tqdm_lib.tqdm(*lowercase , **lowercase ) else: return EmptyTqdm(*lowercase , **lowercase ) def A ( self : Optional[Any] , *lowercase : Tuple , **lowercase : Any ) -> Any: '''simple docstring''' UpperCamelCase__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*lowercase , **lowercase ) def A ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if _tqdm_active: return tqdm_lib.tqdm.get_lock() lowerCamelCase_ : int = _tqdm_cls() def __magic_name__( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def __magic_name__( ): '''simple docstring''' global _tqdm_active UpperCamelCase__ = True def __magic_name__( ): '''simple docstring''' global _tqdm_active UpperCamelCase__ = False
265
0
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
51
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCamelCase (a_ :List[Any] , a_ :Union[str, Any] , a_ :Tuple , a_ :List[str] , a_ :str=True , a_ :str="pt") -> List[str]: lowercase :Optional[int] = {'''add_prefix_space''': True} if isinstance(a_ , a_) and not line.startswith(''' ''') else {} lowercase :Optional[int] = padding_side return tokenizer( [line] , max_length=a_ , padding='''max_length''' if pad_to_max_length else None , truncation=a_ , return_tensors=a_ , add_special_tokens=a_ , **a_ , ) def lowerCamelCase (a_ :str , a_ :Tuple , a_ :Optional[Any]=None , ) -> Tuple: lowercase :Optional[Any] = input_ids.ne(a_).any(dim=0) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __magic_name__ ( __UpperCAmelCase ): def __init__( self : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : str="train" , snake_case__ : Optional[Any]=None , snake_case__ : Tuple=None , snake_case__ : Any=None , snake_case__ : Dict="" , ): '''simple docstring''' super().__init__() lowercase :Tuple = Path(snake_case__ ).joinpath(type_path + '''.source''' ) lowercase :Union[str, Any] = Path(snake_case__ ).joinpath(type_path + '''.target''' ) lowercase :List[Any] = self.get_char_lens(self.src_file ) lowercase :Tuple = max_source_length lowercase :Optional[int] = max_target_length assert min(self.src_lens ) > 0, f"""found empty line in {self.src_file}""" lowercase :Any = tokenizer lowercase :Tuple = prefix if n_obs is not None: lowercase :List[str] = self.src_lens[:n_obs] lowercase :List[Any] = src_lang lowercase :str = tgt_lang def __len__( self : Any ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self : str , snake_case__ : Any ): '''simple docstring''' lowercase :Optional[int] = index + 1 # linecache starts at 1 lowercase :Optional[Any] = self.prefix + linecache.getline(str(self.src_file ) , snake_case__ ).rstrip('''\n''' ) lowercase :Dict = linecache.getline(str(self.tgt_file ) , snake_case__ ).rstrip('''\n''' ) assert source_line, f"""empty source line for index {index}""" assert tgt_line, f"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , snake_case__ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right lowercase :Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer ) lowercase :Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer lowercase :Optional[int] = encode_line(snake_case__ , snake_case__ , self.max_source_length , '''right''' ) lowercase :Tuple = encode_line(snake_case__ , snake_case__ , self.max_target_length , '''right''' ) lowercase :List[str] = source_inputs['''input_ids'''].squeeze() lowercase :Optional[Any] = target_inputs['''input_ids'''].squeeze() lowercase :List[str] = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def __snake_case ( snake_case__ : Optional[int] ): '''simple docstring''' return [len(snake_case__ ) for x in Path(snake_case__ ).open().readlines()] def __snake_case ( self : Tuple , snake_case__ : Union[str, Any] ): '''simple docstring''' lowercase :Optional[Any] = torch.stack([x['''input_ids'''] for x in batch] ) lowercase :Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) lowercase :Tuple = torch.stack([x['''decoder_input_ids'''] for x in batch] ) lowercase :str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer.pad_token_id ) lowercase :Optional[int] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer.pad_token_id ) lowercase :List[Any] = trim_batch(snake_case__ , snake_case__ ) lowercase , lowercase :List[str] = trim_batch(snake_case__ , snake_case__ , attention_mask=snake_case__ ) lowercase :Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch UpperCAmelCase = getLogger(__name__) def lowerCamelCase (a_ :List[List]) -> Tuple: return list(itertools.chain.from_iterable(a_)) def lowerCamelCase (a_ :str) -> None: lowercase :List[str] = get_git_info() save_json(a_ , os.path.join(a_ , '''git_log.json''')) def lowerCamelCase (a_ :Optional[int] , a_ :Optional[int] , a_ :Optional[Any]=4 , **a_ :Optional[Any]) -> str: with open(a_ , '''w''') as f: json.dump(a_ , a_ , indent=a_ , **a_) def lowerCamelCase (a_ :Dict) -> Union[str, Any]: with open(a_) as f: return json.load(a_) def lowerCamelCase () -> List[str]: lowercase :Dict = git.Repo(search_parent_directories=a_) lowercase :int = { '''repo_id''': str(a_), '''repo_sha''': str(repo.head.object.hexsha), '''repo_branch''': str(repo.active_branch), '''hostname''': str(socket.gethostname()), } return repo_infos def lowerCamelCase (a_ :Callable , a_ :Iterable) -> List: return list(map(a_ , a_)) def lowerCamelCase (a_ :Optional[Any] , a_ :str) -> Any: with open(a_ , '''wb''') as f: return pickle.dump(a_ , a_) def lowerCamelCase (a_ :List[str]) -> List[str]: def remove_articles(a_ :Union[str, Any]): return re.sub(R'''\b(a|an|the)\b''' , ''' ''' , a_) def white_space_fix(a_ :Tuple): return " ".join(text.split()) def remove_punc(a_ :int): lowercase :List[Any] = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(a_ :int): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(a_)))) def lowerCamelCase (a_ :List[str] , a_ :Any) -> List[str]: lowercase :Dict = normalize_answer(a_).split() lowercase :int = normalize_answer(a_).split() lowercase :List[Any] = Counter(a_) & Counter(a_) lowercase :Optional[int] = sum(common.values()) if num_same == 0: return 0 lowercase :str = 1.0 * num_same / len(a_) lowercase :Tuple = 1.0 * num_same / len(a_) lowercase :Tuple = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase (a_ :Tuple , a_ :Optional[Any]) -> List[Any]: return normalize_answer(a_) == normalize_answer(a_) def lowerCamelCase (a_ :List[str] , a_ :List[str]) -> Dict: assert len(a_) == len(a_) lowercase :Any = 0 for hypo, pred in zip(a_ , a_): em += exact_match_score(a_ , a_) if len(a_) > 0: em /= len(a_) return {"em": em} def lowerCamelCase (a_ :Union[str, Any]) -> Optional[Any]: return model_prefix.startswith('''rag''') def lowerCamelCase (a_ :List[str] , a_ :Tuple , a_ :List[str]) -> Any: lowercase :List[str] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead lowercase :str = '''dropout_rate''' for p in extra_params: if getattr(a_ , a_ , a_): if not hasattr(a_ , a_) and not hasattr(a_ , equivalent_param[p]): logger.info('''config doesn\'t have a `{}` attribute'''.format(a_)) delattr(a_ , a_) continue lowercase :List[str] = p if hasattr(a_ , a_) else equivalent_param[p] setattr(a_ , a_ , getattr(a_ , a_)) delattr(a_ , a_) return hparams, config
677
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) A = { 'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv2Config'], 'processing_layoutlmv2': ['LayoutLMv2Processor'], 'tokenization_layoutlmv2': ['LayoutLMv2Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['LayoutLMv2TokenizerFast'] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['LayoutLMv2FeatureExtractor'] A = ['LayoutLMv2ImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ 'LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv2ForQuestionAnswering', 'LayoutLMv2ForSequenceClassification', 'LayoutLMv2ForTokenClassification', 'LayoutLMv2Layer', 'LayoutLMv2Model', 'LayoutLMv2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
97
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' UpperCAmelCase__ : Optional[Union[str, Path]] = None UpperCAmelCase__ : bool = False UpperCAmelCase__ : bool = False UpperCAmelCase__ : bool = False UpperCAmelCase__ : Optional[Dict] = None UpperCAmelCase__ : Optional[str] = None UpperCAmelCase__ : bool = False UpperCAmelCase__ : bool = False UpperCAmelCase__ : bool = False UpperCAmelCase__ : bool = True UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : int = 1 UpperCAmelCase__ : Optional[Union[str, bool]] = None UpperCAmelCase__ : bool = False UpperCAmelCase__ : Optional[Dict] = None UpperCAmelCase__ : Optional[str] = None def __snake_case ( self ): return self.__class__(**{k: copy.deepcopy(UpperCamelCase__ ) for k, v in self.__dict__.items()} )
97
1
"""simple docstring""" from math import isqrt def lowerCAmelCase ( __UpperCamelCase ): '''simple docstring''' return all(number % divisor != 0 for divisor in range(2 , isqrt(__UpperCamelCase ) + 1 ) ) def lowerCAmelCase ( __UpperCamelCase = 10**6 ): '''simple docstring''' UpperCAmelCase__ : str = 0 UpperCAmelCase__ : Dict = 1 UpperCAmelCase__ : Optional[Any] = 7 while prime_candidate < max_prime: primes_count += is_prime(__UpperCamelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
65
'''simple docstring''' import gc import threading import time import psutil import torch class __UpperCAmelCase : def __init__( self ): lowerCAmelCase_ = psutil.Process() lowerCAmelCase_ = False def UpperCAmelCase_ ( self ): lowerCAmelCase_ = -1 while True: lowerCAmelCase_ = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCAmelCase_ ( self ): lowerCAmelCase_ = True lowerCAmelCase_ = threading.Thread(target=self.peak_monitor ) lowerCAmelCase_ = True self.thread.start() def UpperCAmelCase_ ( self ): lowerCAmelCase_ = False self.thread.join() return self.cpu_memory_peak A_ : List[str] =PeakCPUMemory() def snake_case_ ( ) -> Tuple: # Time lowerCAmelCase_ = {'''time''': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem lowerCAmelCase_ = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count()): lowerCAmelCase_ = torch.cuda.memory_allocated(__snake_case) torch.cuda.reset_peak_memory_stats() return measures def snake_case_ ( __snake_case : Any) -> List[str]: # Time lowerCAmelCase_ = {'''time''': time.time() - start_measures['''time''']} gc.collect() torch.cuda.empty_cache() # CPU mem lowerCAmelCase_ = (psutil.Process().memory_info().rss - start_measures['''cpu''']) / 2**20 lowerCAmelCase_ = (cpu_peak_tracker.stop() - start_measures['''cpu''']) / 2**20 # GPU mem for i in range(torch.cuda.device_count()): lowerCAmelCase_ = (torch.cuda.memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20 lowerCAmelCase_ = (torch.cuda.max_memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20 return measures def snake_case_ ( __snake_case : Dict , __snake_case : Optional[int]) -> Dict: print(F'''{description}:''') print(F'''- Time: {measures['time']:.2f}s''') for i in range(torch.cuda.device_count()): print(F'''- GPU {i} allocated: {measures[str(__snake_case)]:.2f}MiB''') lowerCAmelCase_ = measures[F'''{i}-peak'''] print(F'''- GPU {i} peak: {peak:.2f}MiB''') print(F'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''') print(F'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''')
274
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCAmelCase : Optional[Any] = { 'configuration_lxmert': ['LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LxmertConfig'], 'tokenization_lxmert': ['LxmertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Any = ['LxmertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[int] = [ 'LxmertEncoder', 'LxmertForPreTraining', 'LxmertForQuestionAnswering', 'LxmertModel', 'LxmertPreTrainedModel', 'LxmertVisualFeatureEncoder', 'LxmertXLayer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[Any] = [ '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 __lowerCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
662
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo __lowerCAmelCase : Optional[Any] = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' __lowerCAmelCase : str = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' __lowerCAmelCase : List[Any] = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ (datasets.Metric ): """simple docstring""" def __UpperCAmelCase ( self : int ) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : List[List[List[str]]] , __lowerCamelCase : List[List[str]] , __lowerCamelCase : int = 1 , __lowerCamelCase : int = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=__lowerCamelCase , hypotheses=__lowerCamelCase , min_len=__lowerCamelCase , max_len=__lowerCamelCase ) }
662
1
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class A (unittest.TestCase ): '''simple docstring''' def a_ ( self : Any ) -> Any: """simple docstring""" A__ = """ylacombe/bark-small""" A__ = tempfile.mkdtemp() A__ = """en_speaker_1""" A__ = """This is a test string""" A__ = """speaker_embeddings_path.json""" A__ = """speaker_embeddings""" def a_ ( self : Optional[Any] , **__lowerCAmelCase : str ) -> Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **_lowerCamelCase ) def a_ ( self : Dict ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def a_ ( self : Any ) -> Any: """simple docstring""" A__ = self.get_tokenizer() A__ = BarkProcessor(tokenizer=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) A__ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def a_ ( self : Tuple ) -> Dict: """simple docstring""" A__ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) A__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) A__ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def a_ ( self : int ) -> Any: """simple docstring""" A__ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) A__ = 35 A__ = 2 A__ = 8 A__ = { """semantic_prompt""": np.ones(_lowerCamelCase ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset A__ = processor(text=self.input_string , voice_preset=_lowerCamelCase ) A__ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file A__ = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(_lowerCamelCase , **_lowerCamelCase ) A__ = processor(text=self.input_string , voice_preset=_lowerCamelCase ) A__ = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub A__ = processor(text=self.input_string , voice_preset=self.voice_preset ) def a_ ( self : Dict ) -> List[Any]: """simple docstring""" A__ = self.get_tokenizer() A__ = BarkProcessor(tokenizer=_lowerCamelCase ) A__ = processor(text=self.input_string ) A__ = tokenizer( self.input_string , padding="""max_length""" , max_length=2_56 , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
176
"""simple docstring""" def lowerCamelCase_ ( __lowerCAmelCase ) -> list: '''simple docstring''' if len(__lowerCAmelCase ) <= 1: return [tuple(__lowerCAmelCase )] lowerCamelCase__ =[] def generate(__lowerCAmelCase , __lowerCAmelCase ): lowerCamelCase__ =[0] * n res.append(tuple(__lowerCAmelCase ) ) lowerCamelCase__ =0 while i < n: if c[i] < i: if i % 2 == 0: lowerCamelCase__ , lowerCamelCase__ =arr[i], arr[0] else: lowerCamelCase__ , lowerCamelCase__ =arr[i], arr[c[i]] res.append(tuple(__lowerCAmelCase ) ) c[i] += 1 lowerCamelCase__ =0 else: lowerCamelCase__ =0 i += 1 generate(len(__lowerCAmelCase ) , __lowerCAmelCase ) return res if __name__ == "__main__": a =input('Enter numbers separated by a comma:\n').strip() a =[int(item) for item in user_input.split(',')] print(heaps(arr))
530
0
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") lowerCAmelCase_ = {"""target_lang""": """fi""", """source_lang""": """en"""} lowerCAmelCase_ = """>>zh<<""" lowerCAmelCase_ = """Helsinki-NLP/""" if is_torch_available(): lowerCAmelCase_ = """pt""" elif is_tf_available(): lowerCAmelCase_ = """tf""" else: lowerCAmelCase_ = """jax""" @require_sentencepiece class _lowerCAmelCase ( __lowerCAmelCase , unittest.TestCase ): A__ = MarianTokenizer A__ = False A__ = True def __magic_name__( self ): super().setUp() lowerCAmelCase__ : Union[str, Any] = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] lowerCAmelCase__ : int = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) lowerCAmelCase__ : Tuple = Path(self.tmpdirname ) save_json(lowerCAmelCase_ , save_dir / VOCAB_FILES_NAMES['''vocab'''] ) save_json(lowerCAmelCase_ , save_dir / VOCAB_FILES_NAMES['''tokenizer_config_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(lowerCAmelCase_ , save_dir / VOCAB_FILES_NAMES['''source_spm'''] ) copyfile(lowerCAmelCase_ , save_dir / VOCAB_FILES_NAMES['''target_spm'''] ) lowerCAmelCase__ : Union[str, Any] = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__( self , **__UpperCAmelCase ): return MarianTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__( self , __UpperCAmelCase ): return ( "This is a test", "This is a test", ) def __magic_name__( self ): lowerCAmelCase__ : Any = '''</s>''' lowerCAmelCase__ : Tuple = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase_ ) , lowerCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase_ ) , lowerCAmelCase_ ) def __magic_name__( self ): lowerCAmelCase__ : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<pad>''' ) self.assertEqual(len(lowerCAmelCase_ ) , 9 ) def __magic_name__( self ): self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __magic_name__( self ): lowerCAmelCase__ : Tuple = MarianTokenizer.from_pretrained(f"""{ORG_NAME}opus-mt-en-de""" ) lowerCAmelCase__ : List[str] = en_de_tokenizer(['''I am a small frog'''] , return_tensors=lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ : Optional[int] = [38, 121, 14, 697, 3_8848, 0] self.assertListEqual(lowerCAmelCase_ , batch.input_ids[0] ) lowerCAmelCase__ : Optional[Any] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(lowerCAmelCase_ ) lowerCAmelCase__ : Tuple = [x.name for x in Path(lowerCAmelCase_ ).glob('''*''' )] self.assertIn('''source.spm''' , lowerCAmelCase_ ) MarianTokenizer.from_pretrained(lowerCAmelCase_ ) def __magic_name__( self ): lowerCAmelCase__ : Any = self.get_tokenizer() lowerCAmelCase__ : Optional[Any] = tok( ['''I am a small frog''' * 1000, '''I am a small frog'''] , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def __magic_name__( self ): lowerCAmelCase__ : Tuple = self.get_tokenizer() lowerCAmelCase__ : str = tok(['''I am a tiny frog''', '''I am a small frog'''] , padding=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def __magic_name__( self ): # fmt: off lowerCAmelCase__ : Optional[Any] = {'''input_ids''': [[4_3495, 462, 20, 4_2164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 3_8999, 6, 8, 464, 132, 1703, 492, 13, 4669, 3_7867, 13, 7525, 27, 1593, 988, 13, 3_3972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 1_2338, 2, 1_3958, 387, 2, 3629, 6953, 188, 2900, 2, 1_3958, 8011, 1_1501, 23, 8460, 4073, 3_4009, 20, 435, 1_1439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 3_7867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 2_6453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 1_0767, 6, 316, 304, 4239, 3, 0], [148, 1_5722, 19, 1839, 12, 1350, 13, 2_2327, 5082, 5418, 4_7567, 3_5938, 59, 318, 1_9552, 108, 2183, 54, 1_4976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 1_9088, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100], [36, 6395, 1_2570, 3_9147, 1_1597, 6, 266, 4, 4_5405, 7296, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase_ , model_name='''Helsinki-NLP/opus-mt-en-de''' , revision='''1a8c2263da11e68e50938f97e10cd57820bd504c''' , decode_kwargs={'''use_source_tokenizer''': True} , ) def __magic_name__( self ): lowerCAmelCase__ : Optional[Any] = MarianTokenizer.from_pretrained('''hf-internal-testing/test-marian-two-vocabs''' ) lowerCAmelCase__ : Any = '''Tämä on testi''' lowerCAmelCase__ : str = '''This is a test''' lowerCAmelCase__ : str = [76, 7, 2047, 2] lowerCAmelCase__ : int = [69, 12, 11, 940, 2] lowerCAmelCase__ : Any = tokenizer(lowerCAmelCase_ ).input_ids self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ : Union[str, Any] = tokenizer(text_target=lowerCAmelCase_ ).input_ids self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ : List[Any] = tokenizer.decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ )
717
import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor lowerCAmelCase_ = logging.get_logger(__name__) class _lowerCAmelCase ( _lowercase ): def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ): warnings.warn( '''The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use OwlViTImageProcessor instead.''' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
470
0
'''simple docstring''' import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef UpperCamelCase__ = ( 'This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ' 'library. You can have a look at this example script for pointers: ' 'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py' ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" warnings.warn(_UpperCamelCase , _UpperCamelCase ) requires_backends(_UpperCamelCase , "sklearn" ) return (preds == labels).mean() def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" warnings.warn(_UpperCamelCase , _UpperCamelCase ) requires_backends(_UpperCamelCase , "sklearn" ) lowercase_ : Optional[int] = simple_accuracy(_UpperCamelCase , _UpperCamelCase ) lowercase_ : Dict = fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" warnings.warn(_UpperCamelCase , _UpperCamelCase ) requires_backends(_UpperCamelCase , "sklearn" ) lowercase_ : Union[str, Any] = pearsonr(_UpperCamelCase , _UpperCamelCase )[0] lowercase_ : int = spearmanr(_UpperCamelCase , _UpperCamelCase )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" warnings.warn(_UpperCamelCase , _UpperCamelCase ) requires_backends(_UpperCamelCase , "sklearn" ) assert len(_UpperCamelCase ) == len(_UpperCamelCase ), F"""Predictions and labels have mismatched lengths {len(_UpperCamelCase )} and {len(_UpperCamelCase )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(_UpperCamelCase , _UpperCamelCase )} elif task_name == "sst-2": return {"acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} elif task_name == "mrpc": return acc_and_fa(_UpperCamelCase , _UpperCamelCase ) elif task_name == "sts-b": return pearson_and_spearman(_UpperCamelCase , _UpperCamelCase ) elif task_name == "qqp": return acc_and_fa(_UpperCamelCase , _UpperCamelCase ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} elif task_name == "qnli": return {"acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} elif task_name == "rte": return {"acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} elif task_name == "wnli": return {"acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} elif task_name == "hans": return {"acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} else: raise KeyError(_UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" warnings.warn(_UpperCamelCase , _UpperCamelCase ) requires_backends(_UpperCamelCase , "sklearn" ) if len(_UpperCamelCase ) != len(_UpperCamelCase ): raise ValueError(F"""Predictions and labels have mismatched lengths {len(_UpperCamelCase )} and {len(_UpperCamelCase )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(_UpperCamelCase , _UpperCamelCase )} else: raise KeyError(_UpperCamelCase )
620
'''simple docstring''' import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class _UpperCAmelCase ( snake_case , unittest.TestCase ): __lowerCamelCase: Optional[int] = BertTokenizer __lowerCamelCase: Optional[int] = BertTokenizerFast __lowerCamelCase: Union[str, Any] = True __lowerCamelCase: int = True __lowerCamelCase: Optional[Any] = filter_non_english def lowerCAmelCase__ ( self : str ): '''simple docstring''' super().setUp() lowercase_ : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowercase_ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def lowerCAmelCase__ ( self : Any , a : Tuple ): '''simple docstring''' lowercase_ : Tuple = "UNwant\u00E9d,running" lowercase_ : List[str] = "unwanted, running" return input_text, output_text def lowerCAmelCase__ ( self : Dict ): '''simple docstring''' lowercase_ : Optional[int] = self.tokenizer_class(self.vocab_file ) lowercase_ : Union[str, Any] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(a , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , [9, 6, 7, 1_2, 1_0, 1_1] ) def lowerCAmelCase__ ( self : Optional[int] ): '''simple docstring''' if not self.test_rust_tokenizer: return lowercase_ : Optional[Any] = self.get_tokenizer() lowercase_ : Optional[Any] = self.get_rust_tokenizer() lowercase_ : int = "UNwant\u00E9d,running" lowercase_ : Dict = tokenizer.tokenize(a ) lowercase_ : Optional[int] = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) lowercase_ : List[Any] = tokenizer.encode(a , add_special_tokens=a ) lowercase_ : List[Any] = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) lowercase_ : Optional[int] = self.get_rust_tokenizer() lowercase_ : Optional[int] = tokenizer.encode(a ) lowercase_ : Optional[Any] = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) # With lower casing lowercase_ : Tuple = self.get_tokenizer(do_lower_case=a ) lowercase_ : Dict = self.get_rust_tokenizer(do_lower_case=a ) lowercase_ : List[Any] = "UNwant\u00E9d,running" lowercase_ : str = tokenizer.tokenize(a ) lowercase_ : Optional[Any] = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) lowercase_ : Any = tokenizer.encode(a , add_special_tokens=a ) lowercase_ : str = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) lowercase_ : Union[str, Any] = self.get_rust_tokenizer() lowercase_ : Tuple = tokenizer.encode(a ) lowercase_ : Optional[int] = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ : Any = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ : List[Any] = BasicTokenizer(do_lower_case=a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ : Optional[int] = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def lowerCAmelCase__ ( self : Optional[int] ): '''simple docstring''' lowercase_ : Optional[Any] = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def lowerCAmelCase__ ( self : int ): '''simple docstring''' lowercase_ : Union[str, Any] = BasicTokenizer(do_lower_case=a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def lowerCAmelCase__ ( self : Optional[int] ): '''simple docstring''' lowercase_ : str = BasicTokenizer(do_lower_case=a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def lowerCAmelCase__ ( self : Tuple ): '''simple docstring''' lowercase_ : int = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def lowerCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' lowercase_ : Optional[int] = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def lowerCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' lowercase_ : Any = BasicTokenizer(do_lower_case=a , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def lowerCAmelCase__ ( self : str ): '''simple docstring''' lowercase_ : Union[str, Any] = BasicTokenizer() lowercase_ : Optional[int] = "a\n'll !!to?'d of, can't." lowercase_ : List[Any] = ["a", "'", "ll", "!", "!", "to", "?", "'", "d", "of", ",", "can", "'", "t", "."] self.assertListEqual(tokenizer.tokenize(a ) , a ) def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' lowercase_ : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] lowercase_ : int = {} for i, token in enumerate(a ): lowercase_ : Any = i lowercase_ : Union[str, Any] = WordpieceTokenizer(vocab=a , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def lowerCAmelCase__ ( self : List[str] ): '''simple docstring''' self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def lowerCAmelCase__ ( self : Optional[int] ): '''simple docstring''' self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def lowerCAmelCase__ ( self : List[Any] ): '''simple docstring''' self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def lowerCAmelCase__ ( self : List[Any] ): '''simple docstring''' lowercase_ : Dict = self.get_tokenizer() lowercase_ : Optional[Any] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) @slow def lowerCAmelCase__ ( self : int ): '''simple docstring''' lowercase_ : str = self.tokenizer_class.from_pretrained("bert-base-uncased" ) lowercase_ : Tuple = tokenizer.encode("sequence builders" , add_special_tokens=a ) lowercase_ : Union[str, Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=a ) lowercase_ : Dict = tokenizer.build_inputs_with_special_tokens(a ) lowercase_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(a , a ) assert encoded_sentence == [1_0_1] + text + [1_0_2] assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2] def lowerCAmelCase__ ( self : int ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowercase_ : str = self.rust_tokenizer_class.from_pretrained(a , **a ) lowercase_ : Dict = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" lowercase_ : int = tokenizer_r.encode_plus( a , return_attention_mask=a , return_token_type_ids=a , return_offsets_mapping=a , add_special_tokens=a , ) lowercase_ : Tuple = tokenizer_r.do_lower_case if hasattr(a , "do_lower_case" ) else False lowercase_ : List[Any] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def lowerCAmelCase__ ( self : str ): '''simple docstring''' lowercase_ : Tuple = ["的", "人", "有"] lowercase_ : int = "".join(a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowercase_ : str = True lowercase_ : Dict = self.tokenizer_class.from_pretrained(a , **a ) lowercase_ : List[str] = self.rust_tokenizer_class.from_pretrained(a , **a ) lowercase_ : Optional[Any] = tokenizer_p.encode(a , add_special_tokens=a ) lowercase_ : Union[str, Any] = tokenizer_r.encode(a , add_special_tokens=a ) lowercase_ : str = tokenizer_r.convert_ids_to_tokens(a ) lowercase_ : Optional[Any] = tokenizer_p.convert_ids_to_tokens(a ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(a , a ) self.assertListEqual(a , a ) lowercase_ : Tuple = False lowercase_ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(a , **a ) lowercase_ : List[str] = self.tokenizer_class.from_pretrained(a , **a ) lowercase_ : Union[str, Any] = tokenizer_r.encode(a , add_special_tokens=a ) lowercase_ : Optional[Any] = tokenizer_p.encode(a , add_special_tokens=a ) lowercase_ : int = tokenizer_r.convert_ids_to_tokens(a ) lowercase_ : List[Any] = tokenizer_p.convert_ids_to_tokens(a ) # it is expected that only the first Chinese character is not preceded by "##". lowercase_ : int = [ f"""##{token}""" if idx != 0 else token for idx, token in enumerate(a ) ] self.assertListEqual(a , a ) self.assertListEqual(a , a )
620
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a = logging.get_logger(__name__) class a_ ( snake_case ): UpperCAmelCase : Optional[int] = ["""pixel_values"""] def __init__( self : Optional[Any] , a_ : bool = True , a_ : Dict[str, int] = None , a_ : PILImageResampling = PIL.Image.BICUBIC , a_ : bool = True , a_ : Dict[str, int] = None , a_ : Union[int, float] = 1 / 2_5_5 , a_ : bool = True , a_ : bool = True , a_ : Optional[Union[float, List[float]]] = None , a_ : Optional[Union[float, List[float]]] = None , **a_ : Dict , ) -> None: super().__init__(**a_ ) snake_case: str =size if size is not None else {'height': 2_5_6, 'width': 2_5_6} snake_case: List[Any] =get_size_dict(a_ ) snake_case: Union[str, Any] =crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} snake_case: Optional[int] =get_size_dict(a_ , param_name='crop_size' ) snake_case: List[str] =do_resize snake_case: Any =size snake_case: int =resample snake_case: Dict =do_center_crop snake_case: Any =crop_size snake_case: List[str] =do_rescale snake_case: Union[str, Any] =rescale_factor snake_case: Optional[Any] =do_normalize snake_case: Optional[int] =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case: List[Any] =image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase ( self : Optional[int] , a_ : np.ndarray , a_ : Dict[str, int] , a_ : PILImageResampling = PIL.Image.BICUBIC , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Optional[Any] , ) -> np.ndarray: snake_case: str =get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return resize( a_ , size=(size['height'], size['width']) , resample=a_ , data_format=a_ , **a_ ) def UpperCamelCase ( self : Optional[Any] , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Optional[Any] , ) -> np.ndarray: snake_case: Dict =get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return center_crop(a_ , size=(size['height'], size['width']) , data_format=a_ , **a_ ) def UpperCamelCase ( self : Tuple , a_ : np.ndarray , a_ : Union[int, float] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Tuple , ) -> List[Any]: return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def UpperCamelCase ( self : List[Any] , a_ : np.ndarray , a_ : Union[float, List[float]] , a_ : Union[float, List[float]] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Optional[Any] , ) -> np.ndarray: return normalize(a_ , mean=a_ , std=a_ , data_format=a_ , **a_ ) def UpperCamelCase ( self : List[Any] , a_ : ImageInput , a_ : bool = None , a_ : Dict[str, int] = None , a_ : Union[str, Any]=None , a_ : bool = None , a_ : Dict[str, int] = None , a_ : bool = None , a_ : float = None , a_ : bool = None , a_ : Optional[Union[float, List[float]]] = None , a_ : Optional[Union[float, List[float]]] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : ChannelDimension = ChannelDimension.FIRST , **a_ : Optional[int] , ) -> PIL.Image.Image: snake_case: int =do_resize if do_resize is not None else self.do_resize snake_case: List[str] =resample if resample is not None else self.resample snake_case: Union[str, Any] =do_center_crop if do_center_crop is not None else self.do_center_crop snake_case: List[str] =do_rescale if do_rescale is not None else self.do_rescale snake_case: Any =rescale_factor if rescale_factor is not None else self.rescale_factor snake_case: List[Any] =do_normalize if do_normalize is not None else self.do_normalize snake_case: Union[str, Any] =image_mean if image_mean is not None else self.image_mean snake_case: Any =image_std if image_std is not None else self.image_std snake_case: List[Any] =size if size is not None else self.size snake_case: str =get_size_dict(a_ ) snake_case: Optional[int] =crop_size if crop_size is not None else self.crop_size snake_case: List[str] =get_size_dict(a_ , param_name='crop_size' ) snake_case: Dict =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 or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. snake_case: List[str] =[to_numpy_array(a_ ) for image in images] if do_resize: snake_case: Optional[Any] =[self.resize(image=a_ , size=a_ , resample=a_ ) for image in images] if do_center_crop: snake_case: List[str] =[self.center_crop(image=a_ , size=a_ ) for image in images] if do_rescale: snake_case: Optional[Any] =[self.rescale(image=a_ , scale=a_ ) for image in images] if do_normalize: snake_case: List[Any] =[self.normalize(image=a_ , mean=a_ , std=a_ ) for image in images] snake_case: List[Any] =[to_channel_dimension_format(a_ , a_ ) for image in images] snake_case: Optional[int] ={'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
347
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
347
1
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 42 class UpperCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): @register_to_config def __init__( self , _lowerCAmelCase = 32 , _lowerCAmelCase = 64 , _lowerCAmelCase = 20 , _lowerCAmelCase = 768 , _lowerCAmelCase=77 , _lowerCAmelCase=4 , _lowerCAmelCase = 0.0 , _lowerCAmelCase = "silu" , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = "linear" , _lowerCAmelCase = "prd" , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , ): super().__init__() UpperCAmelCase__ : Dict = num_attention_heads UpperCAmelCase__ : Optional[Any] = attention_head_dim UpperCAmelCase__ : List[str] = num_attention_heads * attention_head_dim UpperCAmelCase__ : List[str] = additional_embeddings UpperCAmelCase__ : Tuple = time_embed_dim or inner_dim UpperCAmelCase__ : int = embedding_proj_dim or embedding_dim UpperCAmelCase__ : Tuple = clip_embed_dim or embedding_dim UpperCAmelCase__ : Tuple = Timesteps(_lowerCAmelCase , _lowerCAmelCase , 0 ) UpperCAmelCase__ : int = TimestepEmbedding(_lowerCAmelCase , _lowerCAmelCase , out_dim=_lowerCAmelCase , act_fn=_lowerCAmelCase ) UpperCAmelCase__ : List[str] = nn.Linear(_lowerCAmelCase , _lowerCAmelCase ) if embedding_proj_norm_type is None: UpperCAmelCase__ : Optional[int] = None elif embedding_proj_norm_type == "layer": UpperCAmelCase__ : str = nn.LayerNorm(_lowerCAmelCase ) else: raise ValueError(f"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}" ) UpperCAmelCase__ : List[Any] = nn.Linear(_lowerCAmelCase , _lowerCAmelCase ) if encoder_hid_proj_type is None: UpperCAmelCase__ : str = None elif encoder_hid_proj_type == "linear": UpperCAmelCase__ : List[Any] = nn.Linear(_lowerCAmelCase , _lowerCAmelCase ) else: raise ValueError(f"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}" ) UpperCAmelCase__ : Dict = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _lowerCAmelCase ) ) if added_emb_type == "prd": UpperCAmelCase__ : Tuple = nn.Parameter(torch.zeros(1 , 1 , _lowerCAmelCase ) ) elif added_emb_type is None: UpperCAmelCase__ : Any = None else: raise ValueError( f"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`." ) UpperCAmelCase__ : Dict = nn.ModuleList( [ BasicTransformerBlock( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , dropout=_lowerCAmelCase , activation_fn="""gelu""" , attention_bias=_lowerCAmelCase , ) for d in range(_lowerCAmelCase ) ] ) if norm_in_type == "layer": UpperCAmelCase__ : Optional[Any] = nn.LayerNorm(_lowerCAmelCase ) elif norm_in_type is None: UpperCAmelCase__ : Union[str, Any] = None else: raise ValueError(f"Unsupported norm_in_type: {norm_in_type}." ) UpperCAmelCase__ : Optional[int] = nn.LayerNorm(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = nn.Linear(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : str = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_0_0_0_0.0 ) causal_attention_mask.triu_(1 ) UpperCAmelCase__ : List[str] = causal_attention_mask[None, ...] self.register_buffer("""causal_attention_mask""" , _lowerCAmelCase , persistent=_lowerCAmelCase ) UpperCAmelCase__ : Tuple = nn.Parameter(torch.zeros(1 , _lowerCAmelCase ) ) UpperCAmelCase__ : List[Any] = nn.Parameter(torch.zeros(1 , _lowerCAmelCase ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = {} def fn_recursive_add_processors(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): if hasattr(_lowerCAmelCase , """set_processor""" ): UpperCAmelCase__ : int = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}" , _lowerCAmelCase , _lowerCAmelCase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) return processors def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = len(self.attn_processors.keys() ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and len(_lowerCAmelCase ) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(_lowerCAmelCase )} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): if hasattr(_lowerCAmelCase , """set_processor""" ): if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): module.set_processor(_lowerCAmelCase ) 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}" , _lowerCAmelCase , _lowerCAmelCase ) for name, module in self.named_children(): fn_recursive_attn_processor(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def __UpperCAmelCase ( self ): self.set_attn_processor(AttnProcessor() ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = True , ): UpperCAmelCase__ : List[str] = hidden_states.shape[0] UpperCAmelCase__ : List[str] = timestep if not torch.is_tensor(_lowerCAmelCase ): UpperCAmelCase__ : Tuple = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_lowerCAmelCase ) and len(timesteps.shape ) == 0: UpperCAmelCase__ : List[str] = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCAmelCase__ : Tuple = timesteps * torch.ones(_lowerCAmelCase , dtype=timesteps.dtype , device=timesteps.device ) UpperCAmelCase__ : Tuple = self.time_proj(_lowerCAmelCase ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. UpperCAmelCase__ : Dict = timesteps_projected.to(dtype=self.dtype ) UpperCAmelCase__ : Dict = self.time_embedding(_lowerCAmelCase ) if self.embedding_proj_norm is not None: UpperCAmelCase__ : List[str] = self.embedding_proj_norm(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = self.embedding_proj(_lowerCAmelCase ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: UpperCAmelCase__ : str = self.encoder_hidden_states_proj(_lowerCAmelCase ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" ) UpperCAmelCase__ : List[Any] = self.proj_in(_lowerCAmelCase ) UpperCAmelCase__ : Dict = self.positional_embedding.to(hidden_states.dtype ) UpperCAmelCase__ : Any = [] UpperCAmelCase__ : Any = 0 if encoder_hidden_states is not None: additional_embeds.append(_lowerCAmelCase ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: UpperCAmelCase__ : List[str] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: UpperCAmelCase__ : Tuple = hidden_states[:, None, :] UpperCAmelCase__ : Tuple = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: UpperCAmelCase__ : List[str] = self.prd_embedding.to(hidden_states.dtype ).expand(_lowerCAmelCase , -1 , -1 ) additional_embeds.append(_lowerCAmelCase ) UpperCAmelCase__ : Dict = torch.cat( _lowerCAmelCase , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens UpperCAmelCase__ : int = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: UpperCAmelCase__ : Union[str, Any] = F.pad( _lowerCAmelCase , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) UpperCAmelCase__ : List[Any] = hidden_states + positional_embeddings if attention_mask is not None: UpperCAmelCase__ : str = (1 - attention_mask.to(hidden_states.dtype )) * -1_0_0_0_0.0 UpperCAmelCase__ : Any = F.pad(_lowerCAmelCase , (0, self.additional_embeddings) , value=0.0 ) UpperCAmelCase__ : Dict = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) UpperCAmelCase__ : List[str] = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: UpperCAmelCase__ : int = self.norm_in(_lowerCAmelCase ) for block in self.transformer_blocks: UpperCAmelCase__ : List[Any] = block(_lowerCAmelCase , attention_mask=_lowerCAmelCase ) UpperCAmelCase__ : int = self.norm_out(_lowerCAmelCase ) if self.prd_embedding is not None: UpperCAmelCase__ : Dict = hidden_states[:, -1] else: UpperCAmelCase__ : Optional[Any] = hidden_states[:, additional_embeddings_len:] UpperCAmelCase__ : str = self.proj_to_clip_embeddings(_lowerCAmelCase ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : int = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
79
def snake_case__ ( SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' lowercase__ : int = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def snake_case__ ( SCREAMING_SNAKE_CASE_ : int = 5_000 ): '''simple docstring''' lowercase__ : int = [(i * (3 * i - 1)) // 2 for i in range(1 , SCREAMING_SNAKE_CASE_ )] for i, pentagonal_i in enumerate(SCREAMING_SNAKE_CASE_ ): for j in range(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ): lowercase__ : Tuple = pentagonal_nums[j] lowercase__ : Union[str, Any] = pentagonal_i + pentagonal_j lowercase__ : int = pentagonal_j - pentagonal_i if is_pentagonal(SCREAMING_SNAKE_CASE_ ) and is_pentagonal(SCREAMING_SNAKE_CASE_ ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
164
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' ,'''False''' ) ) is not True ,reason='''Skipping test because should only be run when releasing minor transformers version''' ,) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 16_00, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 16_00, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class __A ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): if self.framework == "pytorch": subprocess.run( F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding="utf-8" , check=_snake_case , ) assert hasattr(self , "env" ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): # configuration for running training on smdistributed Model Parallel _lowerCAmelCase : Optional[int] = { "enabled": True, "processes_per_host": 8, } _lowerCAmelCase : Union[str, Any] = { "enabled": True, "parameters": { "microbatches": 4, "placement_strategy": "spread", "pipeline": "interleaved", "optimize": "speed", "partitions": 4, "ddp": True, }, } _lowerCAmelCase : int = {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options} _lowerCAmelCase : int = "trainer" if self.script == "run_glue.py" else "smtrainer" # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"""{self.env.base_job_name}-{instance_count}-smp-{name_extension}""" , instance_count=_snake_case , instance_type=self.instance_type , debugger_hook_config=_snake_case , hyperparameters={ **self.env.hyperparameters, "model_name_or_path": self.model_name_or_path, "max_steps": 500, } , metric_definitions=self.env.metric_definitions , distribution=_snake_case , py_version="py36" , ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): TrainingJobAnalytics(_snake_case ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(1,)] ) def SCREAMING_SNAKE_CASE__ ( self , _snake_case ): # create estimator _lowerCAmelCase : Tuple = self.create_estimator(_snake_case ) # run training estimator.fit() # result dataframe _lowerCAmelCase : str = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis _lowerCAmelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) _lowerCAmelCase : Union[str, Any] = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping _lowerCAmelCase : List[Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"""{estimator.latest_training_job.name}.json""" , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , _snake_case )
701
def UpperCamelCase_ ( lowerCAmelCase__ = 4_00_00_00 ): """simple docstring""" _lowerCAmelCase : int = [0, 1] _lowerCAmelCase : List[str] = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 _lowerCAmelCase : str = 0 for j in range(len(lowerCAmelCase__ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F'''{solution() = }''')
587
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor __lowercase : List[Any] =logging.get_logger(__name__) class A ( __lowercase ): def __init__( self: List[Any] , *_lowerCAmelCase: Optional[Any] , **_lowerCAmelCase: List[str] ) -> None: '''simple docstring''' warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , _lowerCAmelCase , ) super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
54
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = 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 ) -> Optional[int]: """simple docstring""" pass
680
0
from __future__ import annotations def lowercase_ ( _UpperCamelCase ): '''simple docstring''' if len(_UpperCamelCase ) == 0: return array __lowercase , __lowercase = min(_UpperCamelCase ), max(_UpperCamelCase ) # Compute the variables __lowercase = _max - _min + 1 __lowercase , __lowercase = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: __lowercase = i - _min __lowercase = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. __lowercase = 0 for i in range(_UpperCamelCase ): while holes_repeat[i] > 0: __lowercase = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() a : Union[str, Any] = input('''Enter numbers separated by comma:\n''') a : Dict = [int(x) for x in user_input.split(''',''')] print(pigeon_sort(unsorted))
714
from ..utils import DummyObject, requires_backends class lowerCamelCase_ ( metaclass=lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase = ["speech"] def __init__( self , *snake_case_ , **snake_case_ ) -> List[str]: '''simple docstring''' requires_backends(self , ['''speech'''] ) class lowerCamelCase_ ( metaclass=lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase = ["speech"] def __init__( self , *snake_case_ , **snake_case_ ) -> Tuple: '''simple docstring''' requires_backends(self , ['''speech'''] )
527
0
"""simple docstring""" import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __a ( _lowerCAmelCase ): def _SCREAMING_SNAKE_CASE ( self : Tuple )-> int: """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "neck_hidden_sizes" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "num_attention_heads" ) ) class __a : def __init__( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : int=32 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Dict=640 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Optional[Any]="silu" , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : str=None , )-> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = last_hidden_size UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = conv_kernel_size UpperCamelCase = output_stride UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = classifier_dropout_prob UpperCamelCase = use_labels UpperCamelCase = is_training UpperCamelCase = num_labels UpperCamelCase = initializer_range UpperCamelCase = scope def _SCREAMING_SNAKE_CASE ( self : Optional[Any] )-> int: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels, pixel_labels def _SCREAMING_SNAKE_CASE ( self : Tuple )-> Dict: """simple docstring""" return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any )-> Tuple: """simple docstring""" UpperCamelCase = MobileViTModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int] )-> Optional[Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = MobileViTForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] )-> Any: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = MobileViTForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) UpperCamelCase = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _SCREAMING_SNAKE_CASE ( self : int )-> List[str]: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __a ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): UpperCamelCase_ : List[Any] = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : int = ( { '''feature-extraction''': MobileViTModel, '''image-classification''': MobileViTForImageClassification, '''image-segmentation''': MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : str = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : Optional[int] = False UpperCamelCase_ : Union[str, Any] = False def _SCREAMING_SNAKE_CASE ( self : str )-> Optional[int]: """simple docstring""" UpperCamelCase = MobileViTModelTester(self ) UpperCamelCase = MobileViTConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Any )-> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="MobileViT does not use inputs_embeds" ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> Optional[int]: """simple docstring""" pass @unittest.skip(reason="MobileViT does not support input and output embeddings" ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="MobileViT does not output attentions" ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> Dict: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> str: """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(UpperCAmelCase_ ) 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] , UpperCAmelCase_ ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _SCREAMING_SNAKE_CASE ( self : Any )-> str: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] )-> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> Any: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] ): UpperCamelCase = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 5 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. UpperCamelCase = 2 for i in range(len(UpperCAmelCase_ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Dict )-> Any: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : List[str] )-> Union[str, Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Any )-> Optional[int]: """simple docstring""" for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = MobileViTModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( )-> str: """simple docstring""" UpperCamelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __a ( unittest.TestCase ): @cached_property def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> Optional[int]: """simple docstring""" return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] )-> List[str]: """simple docstring""" UpperCamelCase = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(UpperCAmelCase_ ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase = model(**UpperCAmelCase_ ) # verify the logits UpperCamelCase = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) UpperCamelCase = torch.tensor([-1.9364, -1.2327, -0.4653] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1e-4 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str] )-> List[str]: """simple docstring""" UpperCamelCase = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) UpperCamelCase = model.to(UpperCAmelCase_ ) UpperCamelCase = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase = model(**UpperCAmelCase_ ) UpperCamelCase = outputs.logits # verify the logits UpperCamelCase = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) UpperCamelCase = torch.tensor( [ [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]], [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1e-4 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : int )-> Dict: """simple docstring""" UpperCamelCase = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) UpperCamelCase = model.to(UpperCAmelCase_ ) UpperCamelCase = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase = model(**UpperCAmelCase_ ) UpperCamelCase = outputs.logits.detach().cpu() UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_ , target_sizes=[(50, 60)] ) UpperCamelCase = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCAmelCase_ ) UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_ ) UpperCamelCase = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCAmelCase_ )
554
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE = """MobileNetV1Config""" # Base docstring SCREAMING_SNAKE_CASE = """google/mobilenet_v1_1.0_224""" SCREAMING_SNAKE_CASE = [1, 1_024, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE = """google/mobilenet_v1_1.0_224""" SCREAMING_SNAKE_CASE = """tabby, tabby cat""" SCREAMING_SNAKE_CASE = [ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=None )-> int: """simple docstring""" UpperCamelCase = {} if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): UpperCamelCase = model.mobilenet_va else: UpperCamelCase = model UpperCamelCase = "MobilenetV1/Conv2d_0/" UpperCamelCase = backbone.conv_stem.convolution.weight UpperCamelCase = backbone.conv_stem.normalization.bias UpperCamelCase = backbone.conv_stem.normalization.weight UpperCamelCase = backbone.conv_stem.normalization.running_mean UpperCamelCase = backbone.conv_stem.normalization.running_var for i in range(13 ): UpperCamelCase = i + 1 UpperCamelCase = i * 2 UpperCamelCase = backbone.layer[pt_index] UpperCamelCase = F"MobilenetV1/Conv2d_{tf_index}_depthwise/" UpperCamelCase = pointer.convolution.weight UpperCamelCase = pointer.normalization.bias UpperCamelCase = pointer.normalization.weight UpperCamelCase = pointer.normalization.running_mean UpperCamelCase = pointer.normalization.running_var UpperCamelCase = backbone.layer[pt_index + 1] UpperCamelCase = F"MobilenetV1/Conv2d_{tf_index}_pointwise/" UpperCamelCase = pointer.convolution.weight UpperCamelCase = pointer.normalization.bias UpperCamelCase = pointer.normalization.weight UpperCamelCase = pointer.normalization.running_mean UpperCamelCase = pointer.normalization.running_var if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): UpperCamelCase = "MobilenetV1/Logits/Conv2d_1c_1x1/" UpperCamelCase = model.classifier.weight UpperCamelCase = model.classifier.bias return tf_to_pt_map def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )-> List[str]: """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise # Load weights from TF model UpperCamelCase = tf.train.list_variables(UpperCAmelCase_ ) UpperCamelCase = {} for name, shape in init_vars: logger.info(F"Loading TF weight {name} with shape {shape}" ) UpperCamelCase = tf.train.load_variable(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCamelCase = array # Build TF to PyTorch weights loading map UpperCamelCase = _build_tf_to_pytorch_map(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"Importing {name}" ) if name not in tf_weights: logger.info(F"{name} not in tf pre-trained weights, skipping" ) continue UpperCamelCase = tf_weights[name] if "depthwise_weights" in name: logger.info("Transposing depthwise" ) UpperCamelCase = np.transpose(UpperCAmelCase_ , (2, 3, 0, 1) ) elif "weights" in name: logger.info("Transposing" ) if len(pointer.shape ) == 2: # copying into linear layer UpperCamelCase = array.squeeze().transpose() else: UpperCamelCase = np.transpose(UpperCAmelCase_ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" ) logger.info(F"Initialize PyTorch weight {name} {array.shape}" ) UpperCamelCase = torch.from_numpy(UpperCAmelCase_ ) tf_weights.pop(UpperCAmelCase_ , UpperCAmelCase_ ) tf_weights.pop(name + "/RMSProp" , UpperCAmelCase_ ) tf_weights.pop(name + "/RMSProp_1" , UpperCAmelCase_ ) tf_weights.pop(name + "/ExponentialMovingAverage" , UpperCAmelCase_ ) logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" ) return model def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ )-> torch.Tensor: """simple docstring""" UpperCamelCase , UpperCamelCase = features.shape[-2:] UpperCamelCase , UpperCamelCase = conv_layer.stride UpperCamelCase , UpperCamelCase = conv_layer.kernel_size if in_height % stride_height == 0: UpperCamelCase = max(kernel_height - stride_height , 0 ) else: UpperCamelCase = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: UpperCamelCase = max(kernel_width - stride_width , 0 ) else: UpperCamelCase = max(kernel_width - (in_width % stride_width) , 0 ) UpperCamelCase = pad_along_width // 2 UpperCamelCase = pad_along_width - pad_left UpperCamelCase = pad_along_height // 2 UpperCamelCase = pad_along_height - pad_top UpperCamelCase = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(UpperCAmelCase_ , UpperCAmelCase_ , "constant" , 0.0 ) class __a ( nn.Module ): def __init__( self : List[Any] , UpperCAmelCase_ : MobileNetVaConfig , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool or str] = True , )-> None: """simple docstring""" super().__init__() UpperCamelCase = config if in_channels % groups != 0: raise ValueError(f"Input channels ({in_channels}) are not divisible by {groups} groups." ) if out_channels % groups != 0: raise ValueError(f"Output channels ({out_channels}) are not divisible by {groups} groups." ) UpperCamelCase = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) UpperCamelCase = nn.Convad( in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , kernel_size=UpperCAmelCase_ , stride=UpperCAmelCase_ , padding=UpperCAmelCase_ , groups=UpperCAmelCase_ , bias=UpperCAmelCase_ , padding_mode="zeros" , ) if use_normalization: UpperCamelCase = nn.BatchNormad( num_features=UpperCAmelCase_ , eps=config.layer_norm_eps , momentum=0.9997 , affine=UpperCAmelCase_ , track_running_stats=UpperCAmelCase_ , ) else: UpperCamelCase = None if use_activation: if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): UpperCamelCase = ACTaFN[use_activation] elif isinstance(config.hidden_act , UpperCAmelCase_ ): UpperCamelCase = ACTaFN[config.hidden_act] else: UpperCamelCase = config.hidden_act else: UpperCamelCase = None def _SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase_ : torch.Tensor )-> torch.Tensor: """simple docstring""" if self.config.tf_padding: UpperCamelCase = apply_tf_padding(UpperCAmelCase_ , self.convolution ) UpperCamelCase = self.convolution(UpperCAmelCase_ ) if self.normalization is not None: UpperCamelCase = self.normalization(UpperCAmelCase_ ) if self.activation is not None: UpperCamelCase = self.activation(UpperCAmelCase_ ) return features class __a ( _lowerCAmelCase ): UpperCamelCase_ : List[str] = MobileNetVaConfig UpperCamelCase_ : Dict = load_tf_weights_in_mobilenet_va UpperCamelCase_ : List[str] = '''mobilenet_v1''' UpperCamelCase_ : Optional[int] = '''pixel_values''' UpperCamelCase_ : List[Any] = False def _SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase_ : Union[nn.Linear, nn.Convad] )-> None: """simple docstring""" if isinstance(UpperCAmelCase_ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(UpperCAmelCase_ , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) SCREAMING_SNAKE_CASE = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ SCREAMING_SNAKE_CASE = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , _lowerCAmelCase , ) class __a ( _lowerCAmelCase ): def __init__( self : str , UpperCAmelCase_ : MobileNetVaConfig , UpperCAmelCase_ : bool = True )-> Optional[int]: """simple docstring""" super().__init__(UpperCAmelCase_ ) UpperCamelCase = config UpperCamelCase = 32 UpperCamelCase = max(int(depth * config.depth_multiplier ) , config.min_depth ) UpperCamelCase = MobileNetVaConvLayer( UpperCAmelCase_ , in_channels=config.num_channels , out_channels=UpperCAmelCase_ , kernel_size=3 , stride=2 , ) UpperCamelCase = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] UpperCamelCase = nn.ModuleList() for i in range(13 ): UpperCamelCase = out_channels if strides[i] == 2 or i == 0: depth *= 2 UpperCamelCase = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( UpperCAmelCase_ , in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , kernel_size=3 , stride=strides[i] , groups=UpperCAmelCase_ , ) ) self.layer.append( MobileNetVaConvLayer( UpperCAmelCase_ , in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , kernel_size=1 , ) ) UpperCamelCase = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def _SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase_ : Dict )-> List[str]: """simple docstring""" raise NotImplementedError @add_start_docstrings_to_model_forward(UpperCAmelCase_ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase_ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None , )-> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: """simple docstring""" UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("You have to specify pixel_values" ) UpperCamelCase = self.conv_stem(UpperCAmelCase_ ) UpperCamelCase = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): UpperCamelCase = layer_module(UpperCAmelCase_ ) if output_hidden_states: UpperCamelCase = all_hidden_states + (hidden_states,) UpperCamelCase = hidden_states if self.pooler is not None: UpperCamelCase = torch.flatten(self.pooler(UpperCAmelCase_ ) , start_dim=1 ) else: UpperCamelCase = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase_ , pooler_output=UpperCAmelCase_ , hidden_states=UpperCAmelCase_ , ) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , _lowerCAmelCase , ) class __a ( _lowerCAmelCase ): def __init__( self : str , UpperCAmelCase_ : MobileNetVaConfig )-> None: """simple docstring""" super().__init__(UpperCAmelCase_ ) UpperCamelCase = config.num_labels UpperCamelCase = MobileNetVaModel(UpperCAmelCase_ ) UpperCamelCase = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head UpperCamelCase = nn.Dropout(config.classifier_dropout_prob , inplace=UpperCAmelCase_ ) UpperCamelCase = nn.Linear(UpperCAmelCase_ , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase_ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[bool] = None , )-> Union[tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase = self.mobilenet_va(UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , return_dict=UpperCAmelCase_ ) UpperCamelCase = outputs.pooler_output if return_dict else outputs[1] UpperCamelCase = self.classifier(self.dropout(UpperCAmelCase_ ) ) UpperCamelCase = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: UpperCamelCase = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): UpperCamelCase = "single_label_classification" else: UpperCamelCase = "multi_label_classification" if self.config.problem_type == "regression": UpperCamelCase = MSELoss() if self.num_labels == 1: UpperCamelCase = loss_fct(logits.squeeze() , labels.squeeze() ) else: UpperCamelCase = loss_fct(UpperCAmelCase_ , UpperCAmelCase_ ) elif self.config.problem_type == "single_label_classification": UpperCamelCase = CrossEntropyLoss() UpperCamelCase = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": UpperCamelCase = BCEWithLogitsLoss() UpperCamelCase = loss_fct(UpperCAmelCase_ , UpperCAmelCase_ ) if not return_dict: UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=UpperCAmelCase_ , logits=UpperCAmelCase_ , hidden_states=outputs.hidden_states , )
554
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : List[str] =logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] ="""▁""" __lowerCAmelCase : int ={"""vocab_file""": """sentencepiece.bpe.model"""} __lowerCAmelCase : int ={ """vocab_file""": { """facebook/mbart-large-50-one-to-many-mmt""": ( """https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model""" ), } } __lowerCAmelCase : List[Any] ={ """facebook/mbart-large-50-one-to-many-mmt""": 1_0_2_4, } # fmt: off __lowerCAmelCase : Optional[Any] =["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN""", """af_ZA""", """az_AZ""", """bn_IN""", """fa_IR""", """he_IL""", """hr_HR""", """id_ID""", """ka_GE""", """km_KH""", """mk_MK""", """ml_IN""", """mn_MN""", """mr_IN""", """pl_PL""", """ps_AF""", """pt_XX""", """sv_SE""", """sw_KE""", """ta_IN""", """te_IN""", """th_TH""", """tl_XX""", """uk_UA""", """ur_PK""", """xh_ZA""", """gl_ES""", """sl_SI"""] class _A ( lowerCAmelCase ): snake_case__ : Optional[Any] = VOCAB_FILES_NAMES snake_case__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : List[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[str] = ['input_ids', 'attention_mask'] snake_case__ : List[int] = [] snake_case__ : List[int] = [] def __init__( self , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase="</s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="<s>" , __lowerCAmelCase="<unk>" , __lowerCAmelCase="<pad>" , __lowerCAmelCase="<mask>" , __lowerCAmelCase = None , **__lowerCAmelCase , ): """simple docstring""" lowercase = AddedToken(__lowerCAmelCase , lstrip=__lowerCAmelCase , rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else mask_token lowercase = {} if sp_model_kwargs is None else sp_model_kwargs lowercase = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__lowerCAmelCase , tgt_lang=__lowerCAmelCase , eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowerCAmelCase ) ) lowercase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase = 1 lowercase = len(self.sp_model ) lowercase = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__lowerCAmelCase ) } lowercase = {v: k for k, v in self.lang_code_to_id.items()} lowercase = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase = src_lang if src_lang is not None else """en_XX""" lowercase = self.lang_code_to_id[self._src_lang] lowercase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def A__ ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def A__ ( self ): """simple docstring""" return self._src_lang @src_lang.setter def A__ ( self , __lowerCAmelCase ): """simple docstring""" lowercase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase = self.__dict__.copy() lowercase = None return state def __setstate__( self , __lowerCAmelCase ): """simple docstring""" lowercase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowercase = {} lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A__ ( self ): """simple docstring""" lowercase = {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A__ ( self , __lowerCAmelCase ): """simple docstring""" return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def A__ ( self , __lowerCAmelCase ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase = self.sp_model.PieceToId(__lowerCAmelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def A__ ( self , __lowerCAmelCase ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def A__ ( self , __lowerCAmelCase ): """simple docstring""" lowercase = [] lowercase = """""" lowercase = 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(__lowerCAmelCase ) + token lowercase = True lowercase = [] else: current_sub_tokens.append(__lowerCAmelCase ) lowercase = False out_string += self.sp_model.decode(__lowerCAmelCase ) return out_string.strip() def A__ ( self , __lowerCAmelCase , __lowerCAmelCase = None ): """simple docstring""" if not os.path.isdir(__lowerCAmelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowercase = os.path.join( __lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__lowerCAmelCase , """wb""" ) as fi: lowercase = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (out_vocab_file,) def A__ ( self , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCAmelCase , token_ids_a=__lowerCAmelCase , already_has_special_tokens=__lowerCAmelCase ) lowercase = [1] * len(self.prefix_tokens ) lowercase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__lowerCAmelCase )) + suffix_ones return prefix_ones + ([0] * len(__lowerCAmelCase )) + ([0] * len(__lowerCAmelCase )) + suffix_ones def A__ ( self , __lowerCAmelCase , __lowerCAmelCase = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def A__ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) lowercase = src_lang lowercase = self(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase ) lowercase = self.convert_tokens_to_ids(__lowerCAmelCase ) lowercase = tgt_lang_id return inputs def A__ ( self , __lowerCAmelCase , __lowerCAmelCase = "en_XX" , __lowerCAmelCase = None , __lowerCAmelCase = "ro_RO" , **__lowerCAmelCase , ): """simple docstring""" lowercase = src_lang lowercase = tgt_lang return super().prepare_seqaseq_batch(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) def A__ ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def A__ ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def A__ ( self , __lowerCAmelCase ): """simple docstring""" lowercase = self.lang_code_to_id[src_lang] lowercase = [self.cur_lang_code_id] lowercase = [self.eos_token_id] def A__ ( self , __lowerCAmelCase ): """simple docstring""" lowercase = self.lang_code_to_id[tgt_lang] lowercase = [self.cur_lang_code_id] lowercase = [self.eos_token_id]
197
"""simple docstring""" import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase__ ( lowerCAmelCase__ :str ) -> Optional[int]: '''simple docstring''' return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase__ ( lowerCAmelCase__ :Any , lowerCAmelCase__ :Union[str, Any] ) -> str: '''simple docstring''' lowercase = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue lowercase = key.replace("""heads.cmd.mim_head.cls.predictions""" , """mmm_image_head""" ) lowercase = key.replace("""heads.cmd.mlm_head.cls.predictions""" , """mmm_text_head""" ) lowercase = key.replace("""heads.cmd.itm_head.cls""" , """itm_head""" ) lowercase = key.replace("""heads.cmd.itm_head.pooler""" , """itm_head.pooler""" ) lowercase = key.replace("""heads.cmd.clip_head.logit_scale""" , """flava.logit_scale""" ) lowercase = key.replace("""heads.fairseq_mlm.cls.predictions""" , """mlm_head""" ) lowercase = key.replace("""heads.imagenet.mim_head.cls.predictions""" , """mim_head""" ) lowercase = key.replace("""mm_text_projection""" , """flava.text_to_mm_projection""" ) lowercase = key.replace("""mm_image_projection""" , """flava.image_to_mm_projection""" ) lowercase = key.replace("""image_encoder.module""" , """flava.image_model""" ) lowercase = key.replace("""text_encoder.module""" , """flava.text_model""" ) lowercase = key.replace("""mm_encoder.module.encoder.cls_token""" , """flava.multimodal_model.cls_token""" ) lowercase = key.replace("""mm_encoder.module""" , """flava.multimodal_model""" ) lowercase = key.replace("""text_projection""" , """flava.text_projection""" ) lowercase = key.replace("""image_projection""" , """flava.image_projection""" ) lowercase = value.float() for key, value in codebook_state_dict.items(): lowercase = value return upgrade @torch.no_grad() def UpperCAmelCase__ ( lowerCAmelCase__ :Union[str, Any] , lowerCAmelCase__ :Dict , lowerCAmelCase__ :Optional[int] , lowerCAmelCase__ :str=None ) -> int: '''simple docstring''' if config_path is not None: lowercase = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: lowercase = FlavaConfig() lowercase = FlavaForPreTraining(lowerCAmelCase__ ).eval() lowercase = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): lowercase = torch.load(lowerCAmelCase__ , map_location="""cpu""" ) else: lowercase = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location="""cpu""" ) lowercase = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) lowercase = hf_model.state_dict() lowercase = count_parameters(lowerCAmelCase__ ) lowercase = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __lowerCAmelCase : Tuple =argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to flava checkpoint""") parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") __lowerCAmelCase : List[str] =parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
197
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) A : List[Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[Any] = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys A : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
176
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class snake_case__ : lowercase__ : int lowercase__ : int class snake_case__ : def __init__( self , lowerCAmelCase__ ) -> Dict: __magic_name__ : list[list[Edge]] = [[] for _ in range(lowerCAmelCase__ )] __magic_name__ : int = size def __getitem__( self , lowerCAmelCase__ ) -> Iterator[Edge]: return iter(self._graph[vertex] ) @property def __magic_name__ ( self ) -> Optional[int]: return self._size def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(lowerCAmelCase__ , lowerCAmelCase__ ) ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int | None: __magic_name__ : Tuple = deque([start_vertex] ) __magic_name__ : list[int | None] = [None] * self.size __magic_name__ : Optional[Any] = 0 while queue: __magic_name__ : str = queue.popleft() __magic_name__ : Any = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: __magic_name__ : List[Any] = current_distance + edge.weight __magic_name__ : Optional[Any] = distances[edge.destination_vertex] if ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and new_distance >= dest_vertex_distance ): continue __magic_name__ : Tuple = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
324
0
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class a__( a__ ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = """umt5""" UpperCAmelCase_ : Optional[Any] = ["""past_key_values"""] def __init__( self , __lowerCAmelCase=250112 , __lowerCAmelCase=512 , __lowerCAmelCase=64 , __lowerCAmelCase=1024 , __lowerCAmelCase=8 , __lowerCAmelCase=None , __lowerCAmelCase=6 , __lowerCAmelCase=32 , __lowerCAmelCase=128 , __lowerCAmelCase=0.1 , __lowerCAmelCase=1E-6 , __lowerCAmelCase=1.0 , __lowerCAmelCase="gated-gelu" , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase="T5Tokenizer" , __lowerCAmelCase=True , __lowerCAmelCase=0 , __lowerCAmelCase=1 , __lowerCAmelCase=0 , **__lowerCAmelCase , ): """simple docstring""" super().__init__( is_encoder_decoder=lowercase__ , tokenizer_class=lowercase__ , tie_word_embeddings=lowercase__ , pad_token_id=lowercase__ , eos_token_id=lowercase__ , decoder_start_token_id=lowercase__ , **lowercase__ , ) lowerCAmelCase = vocab_size lowerCAmelCase = d_model lowerCAmelCase = d_kv lowerCAmelCase = d_ff lowerCAmelCase = num_layers lowerCAmelCase = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase = num_heads lowerCAmelCase = relative_attention_num_buckets lowerCAmelCase = relative_attention_max_distance lowerCAmelCase = dropout_rate lowerCAmelCase = layer_norm_epsilon lowerCAmelCase = initializer_factor lowerCAmelCase = feed_forward_proj lowerCAmelCase = use_cache lowerCAmelCase = self.feed_forward_proj.split("""-""") lowerCAmelCase = act_info[-1] lowerCAmelCase = act_info[0] == '''gated''' if len(lowercase__) > 1 and act_info[0] != "gated" or len(lowercase__) > 2: raise ValueError( f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer." """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """\'gated-gelu\' or \'relu\'""") if feed_forward_proj == "gated-gelu": lowerCAmelCase = '''gelu_new''' @property def a_ ( self): """simple docstring""" return self.d_model @property def a_ ( self): """simple docstring""" return self.num_heads @property def a_ ( self): """simple docstring""" return self.num_layers class a__( a__ ): '''simple docstring''' @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def a_ ( self): """simple docstring""" lowerCAmelCase = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: lowerCAmelCase = '''past_encoder_sequence + sequence''' lowerCAmelCase = {0: '''batch'''} lowerCAmelCase = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: lowerCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} lowerCAmelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(lowercase__ , direction="""inputs""") return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def a_ ( self): """simple docstring""" return 13 @property def a_ ( self): """simple docstring""" return 5E-4
703
'''simple docstring''' # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __lowercase = '''2.13.1''' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('''3.7'''): raise ImportWarning( '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.''' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n''' '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.''' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip __lowercase = concatenate_datasets __lowercase = DownloadConfig __lowercase = DownloadManager __lowercase = DownloadMode __lowercase = DownloadConfig __lowercase = DownloadMode __lowercase = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
605
0
"""simple docstring""" # coding=utf-8 # Copyright 2023 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 platform import sys UpperCAmelCase = """3""" print("""Python version:""", sys.version) print("""OS platform:""", platform.platform()) print("""OS architecture:""", platform.machine()) 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()) except ImportError: print("""Torch version:""", None) try: import transformers print("""transformers version:""", transformers.__version__) except ImportError: print("""transformers version:""", None)
88
'''simple docstring''' 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__": snake_case_ : Tuple = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') snake_case_ : Union[str, Any] = F'''https://www.google.com/search?q={query}&num=100''' snake_case_ : Optional[int] = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: snake_case_ : int = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: snake_case_ : List[str] = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
212
0
import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCamelCase__ ( UpperCAmelCase, unittest.TestCase ): lowerCamelCase_ : Any = BlenderbotSmallTokenizer lowerCamelCase_ : Union[str, Any] = False def UpperCAmelCase_ (self : str ) -> Dict: """simple docstring""" super().setUp() lowerCamelCase_ : int = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] lowerCamelCase_ : int = dict(zip(_snake_case , range(len(_snake_case ) ) ) ) lowerCamelCase_ : Dict = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] lowerCamelCase_ : Union[str, Any] = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} lowerCamelCase_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase_ : Optional[int] = 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(_snake_case ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_snake_case ) ) def UpperCAmelCase_ (self : List[str] , **_snake_case : List[str] ) -> List[str]: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def UpperCAmelCase_ (self : List[Any] , _snake_case : Optional[Any] ) -> List[str]: """simple docstring""" lowerCamelCase_ : Tuple = 'adapt act apte' lowerCamelCase_ : Dict = 'adapt act apte' return input_text, output_text def UpperCAmelCase_ (self : List[str] ) -> List[Any]: """simple docstring""" lowerCamelCase_ : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCamelCase_ : List[str] = 'adapt act apte' lowerCamelCase_ : Dict = ['adapt', 'act', 'ap@@', 'te'] lowerCamelCase_ : List[str] = tokenizer.tokenize(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) lowerCamelCase_ : Union[str, Any] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] lowerCamelCase_ : List[Any] = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case ) , _snake_case ) def UpperCAmelCase_ (self : Union[str, Any] ) -> str: """simple docstring""" lowerCamelCase_ : Dict = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1384] lowerCamelCase_ : List[Any] = 'I am a small frog.' lowerCamelCase_ : int = tok([src_text] , padding=_snake_case , truncation=_snake_case )['input_ids'] lowerCamelCase_ : Optional[Any] = tok.batch_decode(_snake_case , skip_special_tokens=_snake_case , clean_up_tokenization_spaces=_snake_case )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def UpperCAmelCase_ (self : str ) -> Dict: """simple docstring""" lowerCamelCase_ : List[str] = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) lowerCamelCase_ : List[Any] = 'I am a small frog .' lowerCamelCase_ : Tuple = '.' lowerCamelCase_ : str = tok(_snake_case )['input_ids'] lowerCamelCase_ : str = tok(_snake_case )['input_ids'] assert encoded[-1] == encoded_dot[0]
144
from PIL import Image def _a ( lowerCamelCase__ , lowerCamelCase__ ) -> Image: def brightness(lowerCamelCase__ ) -> float: return 1_28 + level + (c - 1_28) if not -255.0 <= level <= 255.0: raise ValueError('level must be between -255.0 (black) and 255.0 (white)' ) return img.point(lowerCamelCase__ ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 UpperCamelCase = change_brightness(img, 1_0_0) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
144
1
def UpperCamelCase ( ) -> Any: for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def UpperCamelCase ( snake_case__ : Union[str, Any] ) -> Any: UpperCamelCase : str = 1 UpperCamelCase : Optional[Any] = 2 while i * i <= n: UpperCamelCase : List[str] = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def UpperCamelCase ( ) -> List[str]: return next(i for i in triangle_number_generator() if count_divisors(snake_case__ ) > 500 ) if __name__ == "__main__": print(solution())
40
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_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 transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class lowerCAmelCase_ ( a__ ): def snake_case_ ( self ) -> Tuple: UpperCamelCase : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'width_multiplier' ) ) class lowerCAmelCase_ : def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=13, SCREAMING_SNAKE_CASE_=64, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_="swish", SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=32, SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=10, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=0.25, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=0.0, ) -> Any: UpperCamelCase : int = parent UpperCamelCase : int = batch_size UpperCamelCase : List[Any] = image_size UpperCamelCase : List[str] = patch_size UpperCamelCase : Optional[int] = num_channels UpperCamelCase : List[str] = make_divisible(512 * width_multiplier, divisor=8 ) UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[int] = conv_kernel_size UpperCamelCase : List[str] = output_stride UpperCamelCase : Union[str, Any] = classifier_dropout_prob UpperCamelCase : List[Any] = use_labels UpperCamelCase : Any = is_training UpperCamelCase : int = num_labels UpperCamelCase : List[Any] = initializer_range UpperCamelCase : Tuple = scope UpperCamelCase : List[str] = width_multiplier UpperCamelCase : Any = ffn_dropout UpperCamelCase : List[Any] = attn_dropout def snake_case_ ( self ) -> int: UpperCamelCase : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : List[str] = None UpperCamelCase : int = None if self.use_labels: UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size], self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels ) UpperCamelCase : List[str] = self.get_config() return config, pixel_values, labels, pixel_labels def snake_case_ ( self ) -> int: return MobileViTVaConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_act=self.hidden_act, conv_kernel_size=self.conv_kernel_size, output_stride=self.output_stride, classifier_dropout_prob=self.classifier_dropout_prob, initializer_range=self.initializer_range, width_multiplier=self.width_multiplier, ffn_dropout=self.ffn_dropout_prob, attn_dropout=self.attn_dropout_prob, ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase : Any = MobileViTVaModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.last_hidden_state.shape, ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase : Optional[int] = self.num_labels UpperCamelCase : Tuple = MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_, labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase : Any = self.num_labels UpperCamelCase : Optional[Any] = MobileViTVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape, ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_, labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape, ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) def snake_case_ ( self ) -> List[Any]: UpperCamelCase : Union[str, Any] = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : str = config_and_inputs UpperCamelCase : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase_ ( a__ , a__ , unittest.TestCase ): UpperCAmelCase__ : Tuple = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) UpperCAmelCase__ : Any = ( { "feature-extraction": MobileViTVaModel, "image-classification": MobileViTVaForImageClassification, "image-segmentation": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : List[str] = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Optional[Any] = False def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : Dict = MobileViTVaModelTester(self ) UpperCamelCase : Optional[Any] = MobileViTVaConfigTester(self, config_class=SCREAMING_SNAKE_CASE_, has_text_modality=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Optional[Any]: self.config_tester.run_common_tests() @unittest.skip(reason='MobileViTV2 does not use inputs_embeds' ) def snake_case_ ( self ) -> Dict: pass @unittest.skip(reason='MobileViTV2 does not support input and output embeddings' ) def snake_case_ ( self ) -> int: pass @unittest.skip(reason='MobileViTV2 does not output attentions' ) def snake_case_ ( self ) -> str: pass @require_torch_multi_gpu @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.' ) def snake_case_ ( self ) -> Dict: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def snake_case_ ( self ) -> Any: pass def snake_case_ ( self ) -> List[str]: UpperCamelCase , UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : str = [*signature.parameters.keys()] UpperCamelCase : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1], SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Tuple: def check_hidden_states_output(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase : List[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Tuple = outputs.hidden_states UpperCamelCase : Dict = 5 self.assertEqual(len(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. UpperCamelCase : Any = 2 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ), [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor], ) divisor *= 2 self.assertEqual(self.model_tester.output_stride, divisor // 2 ) UpperCamelCase , UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Union[str, Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase : Optional[int] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> str: UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) @slow def snake_case_ ( self ) -> Optional[Any]: for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = MobileViTVaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase ( ) -> Tuple: UpperCamelCase : Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class lowerCAmelCase_ ( unittest.TestCase ): @cached_property def snake_case_ ( self ) -> str: return ( MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ) if is_vision_available() else None ) @slow def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : Any = MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ).to( SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.default_image_processor UpperCamelCase : Any = prepare_img() UpperCamelCase : Tuple = image_processor(images=SCREAMING_SNAKE_CASE_, return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase : Tuple = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3], SCREAMING_SNAKE_CASE_, atol=1e-4 ) ) @slow def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : Optional[int] = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) UpperCamelCase : List[str] = model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) UpperCamelCase : Union[str, Any] = prepare_img() UpperCamelCase : Any = image_processor(images=SCREAMING_SNAKE_CASE_, return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase : Tuple = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = outputs.logits # verify the logits UpperCamelCase : Dict = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor( [ [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]], [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]], [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]], ], device=SCREAMING_SNAKE_CASE_, ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3], SCREAMING_SNAKE_CASE_, atol=1e-4 ) ) @slow def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : str = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) UpperCamelCase : Optional[int] = model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) UpperCamelCase : Tuple = prepare_img() UpperCamelCase : int = image_processor(images=SCREAMING_SNAKE_CASE_, return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase : str = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = outputs.logits.detach().cpu() UpperCamelCase : int = image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_, target_sizes=[(50, 60)] ) UpperCamelCase : Optional[int] = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape, SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape, SCREAMING_SNAKE_CASE_ )
40
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE_ = { 'configuration_nllb_moe': [ 'NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NllbMoeConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ 'NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST', 'NllbMoeForConditionalGeneration', 'NllbMoeModel', 'NllbMoePreTrainedModel', 'NllbMoeTop2Router', 'NllbMoeSparseMLP', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
701
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class a ( __lowerCAmelCase ): """simple docstring""" __lowerCAmelCase = """timesformer""" def __init__( self , snake_case_=224 , snake_case_=16 , snake_case_=3 , snake_case_=8 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.0_2 , snake_case_=1e-6 , snake_case_=True , snake_case_="divided_space_time" , snake_case_=0 , **snake_case_ , ): '''simple docstring''' super().__init__(**snake_case_ ) __UpperCAmelCase: Tuple = image_size __UpperCAmelCase: List[Any] = patch_size __UpperCAmelCase: Optional[Any] = num_channels __UpperCAmelCase: int = num_frames __UpperCAmelCase: List[str] = hidden_size __UpperCAmelCase: List[str] = num_hidden_layers __UpperCAmelCase: Dict = num_attention_heads __UpperCAmelCase: List[str] = intermediate_size __UpperCAmelCase: Union[str, Any] = hidden_act __UpperCAmelCase: Dict = hidden_dropout_prob __UpperCAmelCase: Optional[Any] = attention_probs_dropout_prob __UpperCAmelCase: Union[str, Any] = initializer_range __UpperCAmelCase: List[Any] = layer_norm_eps __UpperCAmelCase: int = qkv_bias __UpperCAmelCase: str = attention_type __UpperCAmelCase: Tuple = drop_path_rate
466
0
import numpy as np from transformers import Pipeline def _UpperCamelCase (a__ :Tuple ): """simple docstring""" UpperCamelCase__ = np.max(a__ , axis=-1 , keepdims=a__ ) UpperCamelCase__ = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=a__ ) class __SCREAMING_SNAKE_CASE ( _a ): def _lowerCamelCase ( self , **__lowerCAmelCase ): UpperCamelCase__ = {} if "second_text" in kwargs: UpperCamelCase__ = kwargs["""second_text"""] return preprocess_kwargs, {}, {} def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase=None ): return self.tokenizer(__lowerCAmelCase , text_pair=__lowerCAmelCase , return_tensors=self.framework ) def _lowerCamelCase ( self , __lowerCAmelCase ): return self.model(**__lowerCAmelCase ) def _lowerCamelCase ( self , __lowerCAmelCase ): UpperCamelCase__ = model_outputs.logits[0].numpy() UpperCamelCase__ = softmax(__lowerCAmelCase ) UpperCamelCase__ = np.argmax(__lowerCAmelCase ) UpperCamelCase__ = self.model.config.idalabel[best_class] UpperCamelCase__ = probabilities[best_class].item() UpperCamelCase__ = logits.tolist() return {"label": label, "score": score, "logits": logits}
619
import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) UpperCamelCase__ = getLogger(__name__) def _UpperCamelCase (a__ :Union[str, Any] , a__ :str , a__ :str , a__ :int = 8 , a__ :int = 1024 , a__ :Dict="val" , a__ :Optional[int]=None , a__ :List[str]=False , a__ :Union[str, Any]="summarization" , a__ :str=None , a__ :Optional[Any]=1 , a__ :Dict = None , a__ :List[Any]="" , **a__ :List[str] , ): """simple docstring""" UpperCamelCase__ = str(a__ ) assert local_rank is not None torch.distributed.init_process_group(backend="""nccl""" , rank=a__ ) UpperCamelCase__ = Path(a__ ) UpperCamelCase__ = save_dir.joinpath(f"""rank_{local_rank}_output.json""" ) torch.cuda.set_device(a__ ) UpperCamelCase__ = AutoModelForSeqaSeqLM.from_pretrained(a__ ).cuda() if fpaa: UpperCamelCase__ = model.half() # determine if we need to increase num_beams use_task_specific_params(a__ , a__ ) # update config with task specific params UpperCamelCase__ = generate_kwargs.pop("""num_beams""" , model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: UpperCamelCase__ = num_return_sequences UpperCamelCase__ = AutoTokenizer.from_pretrained(a__ ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. if max_source_length is None: UpperCamelCase__ = tokenizer.model_max_length if prefix is None: UpperCamelCase__ = prefix or getattr(model.config , """prefix""" , """""" ) or """""" UpperCamelCase__ = SeqaSeqDataset( a__ , a__ , a__ , max_target_length=1024 , type_path=a__ , n_obs=a__ , prefix=a__ , **a__ , ) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. UpperCamelCase__ = ds.make_sortish_sampler(a__ , distributed=a__ , add_extra_examples=a__ , shuffle=a__ ) UpperCamelCase__ = DataLoader(a__ , sampler=a__ , batch_size=a__ , collate_fn=ds.collate_fn ) UpperCamelCase__ = [] for batch in tqdm(a__ ): UpperCamelCase__ = model.generate( input_ids=batch["""input_ids"""].to(model.device ) , attention_mask=batch["""attention_mask"""].to(model.device ) , num_return_sequences=a__ , num_beams=a__ , **a__ , ) UpperCamelCase__ = tokenizer.batch_decode(a__ , skip_special_tokens=a__ , clean_up_tokenization_spaces=a__ ) UpperCamelCase__ = batch["""ids"""] if num_return_sequences > 1: UpperCamelCase__ = chunks(a__ , a__ ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(a__ ): results.append({"""pred""": pred, """id""": ids[i].item()} ) save_json(a__ , a__ ) return results, sampler.num_replicas def _UpperCamelCase (): """simple docstring""" UpperCamelCase__ = argparse.ArgumentParser( epilog="""Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate""" ) parser.add_argument("""--data_dir""" , type=a__ , help="""like cnn_dm/test.source""" ) parser.add_argument( """--model_name""" , type=a__ , help="""like facebook/bart-large-cnn,t5-base, etc.""" , default="""sshleifer/distilbart-xsum-12-3""" , ) parser.add_argument("""--save_dir""" , type=a__ , help="""where to save""" , default="""tmp_gen""" ) parser.add_argument("""--max_source_length""" , type=a__ , default=a__ ) parser.add_argument( """--type_path""" , type=a__ , default="""test""" , help="""which subset to evaluate typically train/val/test""" ) parser.add_argument("""--task""" , type=a__ , default="""summarization""" , help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""" , type=a__ , default=8 , required=a__ , help="""batch size""" ) parser.add_argument( """--local_rank""" , type=a__ , default=-1 , required=a__ , help="""should be passed by distributed.launch""" ) parser.add_argument( """--n_obs""" , type=a__ , default=a__ , required=a__ , help="""How many observations. Defaults to all.""" ) parser.add_argument( """--num_return_sequences""" , type=a__ , default=1 , required=a__ , help="""How many sequences to return""" ) parser.add_argument( """--sync_timeout""" , type=a__ , default=600 , required=a__ , help="""How long should master process wait for other processes to finish.""" , ) parser.add_argument("""--src_lang""" , type=a__ , default=a__ , required=a__ ) parser.add_argument("""--tgt_lang""" , type=a__ , default=a__ , required=a__ ) parser.add_argument( """--prefix""" , type=a__ , required=a__ , default=a__ , help="""will be added to the begininng of src examples""" ) parser.add_argument("""--fp16""" , action="""store_true""" ) parser.add_argument("""--debug""" , action="""store_true""" ) UpperCamelCase__ = time.time() UpperCamelCase__ , UpperCamelCase__ = parser.parse_known_args() UpperCamelCase__ = parse_numeric_n_bool_cl_kwargs(a__ ) if generate_kwargs and args.local_rank <= 0: print(f"""parsed the following generate kwargs: {generate_kwargs}""" ) UpperCamelCase__ = Path(args.save_dir + """_tmp""" ) Path(a__ ).mkdir(exist_ok=a__ ) # this handles locking. UpperCamelCase__ = list(json_save_dir.glob("""rank_*.json""" ) ) if intermediate_files: raise ValueError(f"""Found files at {json_save_dir} please move or remove them.""" ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. UpperCamelCase__ = {} if args.src_lang is not None: UpperCamelCase__ = args.src_lang if args.tgt_lang is not None: UpperCamelCase__ = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=a__ ) UpperCamelCase__ , UpperCamelCase__ = eval_data_dir( args.data_dir , a__ , args.model_name , type_path=args.type_path , bs=args.bs , fpaa=args.fpaa , task=args.task , local_rank=args.local_rank , n_obs=args.n_obs , max_source_length=args.max_source_length , num_return_sequences=args.num_return_sequences , prefix=args.prefix , dataset_kwargs=a__ , **a__ , ) if args.local_rank <= 0: UpperCamelCase__ = Path(args.save_dir ) save_dir.mkdir(exist_ok=a__ ) UpperCamelCase__ = gather_results_from_each_node(a__ , a__ , args.sync_timeout ) UpperCamelCase__ = combine_partial_results(a__ ) if args.num_return_sequences > 1: UpperCamelCase__ = save_dir.joinpath("""pseudolabel_results.json""" ) print(f"""Saving aggregated results at {save_path}, intermediate in {json_save_dir}/""" ) save_json(a__ , a__ ) return UpperCamelCase__ = Path(args.data_dir ).joinpath(args.type_path + """.target""" ) with open(a__ ) as f: UpperCamelCase__ = [x.rstrip() for x in f.readlines()][: len(a__ )] # Calculate metrics, save metrics, and save _generations.txt UpperCamelCase__ = """translation""" in args.task UpperCamelCase__ = calculate_bleu if calc_bleu else calculate_rouge UpperCamelCase__ = """bleu""" if calc_bleu else """rouge""" UpperCamelCase__ = score_fn(a__ , a__ ) UpperCamelCase__ = len(a__ ) UpperCamelCase__ = time.time() - start_time UpperCamelCase__ = round(runtime / metrics["""n_obs"""] , 4 ) UpperCamelCase__ = num_replicas # TODO(@stas00): add whatever metadata to metrics UpperCamelCase__ = save_dir.joinpath(f"""{args.type_path}_{metric_name}.json""" ) save_json(a__ , a__ , indent=a__ ) print(a__ ) write_txt_file(a__ , save_dir.joinpath(f"""{args.type_path}_generations.txt""" ) ) if args.debug: write_txt_file(a__ , save_dir.joinpath(f"""{args.type_path}.target""" ) ) else: shutil.rmtree(a__ ) def _UpperCamelCase (a__ :Dict ): """simple docstring""" UpperCamelCase__ = [] for partial_result in partial_results: records.extend(a__ ) UpperCamelCase__ = sorted(a__ , key=lambda a__ : x["id"] ) UpperCamelCase__ = [x["""pred"""] for x in records] return preds def _UpperCamelCase (a__ :List[str] , a__ :str , a__ :List[Any] ): """simple docstring""" UpperCamelCase__ = time.time() logger.info("""waiting for all nodes to finish""" ) UpperCamelCase__ = None while (time.time() - start_wait) < timeout: UpperCamelCase__ = list(save_dir.glob("""rank_*.json""" ) ) if len(a__ ) < num_replicas: continue try: # make sure all json files are fully saved UpperCamelCase__ = lmap(a__ , a__ ) return json_data except JSONDecodeError: continue else: raise TimeoutError("""Rank 0 gave up on waiting for other processes""" ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
619
1
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , __a : Optional[int] , __a : List[Any]=13 , __a : Optional[int]=64 , __a : str=2 , __a : Tuple=3 , __a : str=True , __a : Optional[Any]=True , __a : Union[str, Any]=32 , __a : Optional[int]=5 , __a : Tuple=4 , __a : Optional[Any]=37 , __a : Any="gelu" , __a : str=0.1 , __a : List[Any]=0.1 , __a : str=10 , __a : List[str]=0.02 , __a : Dict=[1, 16, 4, 4] , __a : Tuple=None , ) ->Any: lowerCamelCase_ : Optional[Any] = parent lowerCamelCase_ : List[str] = batch_size lowerCamelCase_ : Dict = image_size lowerCamelCase_ : str = patch_size lowerCamelCase_ : int = num_channels lowerCamelCase_ : Tuple = is_training lowerCamelCase_ : List[Any] = use_labels lowerCamelCase_ : List[Any] = hidden_size lowerCamelCase_ : Dict = num_hidden_layers lowerCamelCase_ : Optional[int] = num_attention_heads lowerCamelCase_ : int = intermediate_size lowerCamelCase_ : List[Any] = hidden_act lowerCamelCase_ : Union[str, Any] = hidden_dropout_prob lowerCamelCase_ : Optional[Any] = attention_probs_dropout_prob lowerCamelCase_ : Union[str, Any] = type_sequence_label_size lowerCamelCase_ : Optional[Any] = initializer_range lowerCamelCase_ : List[Any] = scope lowerCamelCase_ : Dict = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size lowerCamelCase_ : Optional[int] = (self.image_size // 32) ** 2 lowerCamelCase_ : Optional[int] = num_patches + 1 def _lowerCAmelCase ( self : Optional[int] ) ->int: lowerCamelCase_ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ : int = None if self.use_labels: lowerCamelCase_ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase_ : Optional[int] = self.get_config() return config, pixel_values, labels def _lowerCAmelCase ( self : int ) ->List[str]: lowerCamelCase_ : int = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [4, 8, 16, 32], """num_groups""": 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=__a , ) def _lowerCAmelCase ( self : Union[str, Any] , __a : List[str] , __a : Any , __a : int ) ->Optional[int]: lowerCamelCase_ : int = ViTHybridModel(config=__a ) model.to(__a ) model.eval() lowerCamelCase_ : Optional[Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Dict , __a : Dict , __a : Optional[int] , __a : str ) ->str: lowerCamelCase_ : Union[str, Any] = self.type_sequence_label_size lowerCamelCase_ : int = ViTHybridForImageClassification(__a ) model.to(__a ) model.eval() lowerCamelCase_ : Optional[Any] = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ) ->Any: lowerCamelCase_ : List[Any] = self.prepare_config_and_inputs() lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ : str = config_and_inputs lowerCamelCase_ : str = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ (a__ , a__ , unittest.TestCase ): '''simple docstring''' _a = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () _a = ( {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False def _lowerCAmelCase ( self : List[str] ) ->int: lowerCamelCase_ : str = ViTHybridModelTester(self ) lowerCamelCase_ : Dict = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def _lowerCAmelCase ( self : str ) ->List[Any]: self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def _lowerCAmelCase ( self : str ) ->Optional[int]: pass def _lowerCAmelCase ( self : Optional[Any] ) ->Tuple: lowerCamelCase_, lowerCamelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : Any = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase_ : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def _lowerCAmelCase ( self : Tuple ) ->Optional[Any]: lowerCamelCase_, lowerCamelCase_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : Optional[Any] = model_class(__a ) lowerCamelCase_ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ : Tuple = [*signature.parameters.keys()] lowerCamelCase_ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __a ) def _lowerCAmelCase ( self : Dict ) ->List[str]: lowerCamelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def _lowerCAmelCase ( self : int ) ->List[str]: lowerCamelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) def _lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: lowerCamelCase_, lowerCamelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase_ : Optional[Any] = _config_zero_init(__a ) for model_class in self.all_model_classes: lowerCamelCase_ : Optional[Any] = model_class(config=__a ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": lowerCamelCase_ : Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def _lowerCAmelCase ( self : Any ) ->Tuple: for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ : Optional[int] = ViTHybridModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def __lowerCamelCase ( ) -> Union[str, Any]: lowerCamelCase_ : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE_ (unittest.TestCase ): '''simple docstring''' @cached_property def _lowerCAmelCase ( self : Dict ) ->Union[str, Any]: return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _lowerCAmelCase ( self : List[Any] ) ->List[str]: lowerCamelCase_ : Union[str, Any] = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __a ) lowerCamelCase_ : Optional[int] = self.default_image_processor lowerCamelCase_ : List[str] = prepare_img() lowerCamelCase_ : Any = image_processor(images=__a , return_tensors="""pt""" ).to(__a ) # forward pass with torch.no_grad(): lowerCamelCase_ : Optional[Any] = model(**__a ) # verify the logits lowerCamelCase_ : Tuple = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , __a ) lowerCamelCase_ : Any = torch.tensor([-1.9_090, -0.4_993, -0.2_389] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) ) @slow @require_accelerate def _lowerCAmelCase ( self : str ) ->Dict: lowerCamelCase_ : Tuple = ViTHybridImageProcessor.from_pretrained("""google/vit-hybrid-base-bit-384""" ) lowerCamelCase_ : Optional[Any] = ViTHybridForImageClassification.from_pretrained("""google/vit-hybrid-base-bit-384""" , device_map="""auto""" ) lowerCamelCase_ : str = prepare_img() lowerCamelCase_ : List[Any] = image_processor(images=__a , return_tensors="""pt""" ) lowerCamelCase_ : Optional[int] = model(**__a ) lowerCamelCase_ : Dict = outputs.logits # model predicts one of the 1000 ImageNet classes lowerCamelCase_ : List[str] = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , """tabby, tabby cat""" )
171
import qiskit def __lowerCamelCase ( A__ : int = 2 ) -> qiskit.result.counts.Counts: lowerCamelCase_ : List[Any] = qubits # Using Aer's simulator lowerCamelCase_ : Tuple = qiskit.Aer.get_backend("""aer_simulator""" ) # Creating a Quantum Circuit acting on the q register lowerCamelCase_ : int = qiskit.QuantumCircuit(A__ , A__ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , A__ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , A__ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(A__ ) ) , list(range(A__ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator lowerCamelCase_ : Union[str, Any] = qiskit.execute(A__ , A__ , shots=1000 ) return job.result().get_counts(A__ ) if __name__ == "__main__": print(F'Total count for various states are: {quantum_entanglement(3)}')
171
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a = logging.get_logger(__name__) a = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class lowercase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCAmelCase : List[Any] = '''big_bird''' def __init__( self : Any , _UpperCAmelCase : List[str]=50_358 , _UpperCAmelCase : Union[str, Any]=768 , _UpperCAmelCase : Optional[Any]=12 , _UpperCAmelCase : Any=12 , _UpperCAmelCase : List[str]=3_072 , _UpperCAmelCase : str="gelu_new" , _UpperCAmelCase : str=0.1 , _UpperCAmelCase : str=0.1 , _UpperCAmelCase : Optional[int]=4_096 , _UpperCAmelCase : Tuple=2 , _UpperCAmelCase : str=0.02 , _UpperCAmelCase : str=1E-1_2 , _UpperCAmelCase : Any=True , _UpperCAmelCase : List[Any]=0 , _UpperCAmelCase : Union[str, Any]=1 , _UpperCAmelCase : List[Any]=2 , _UpperCAmelCase : List[str]=66 , _UpperCAmelCase : Optional[int]="block_sparse" , _UpperCAmelCase : int=True , _UpperCAmelCase : Dict=False , _UpperCAmelCase : Any=64 , _UpperCAmelCase : Tuple=3 , _UpperCAmelCase : Tuple=None , **_UpperCAmelCase : List[str] , ): super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , sep_token_id=a_ , **a_ , ) _A = vocab_size _A = max_position_embeddings _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = initializer_range _A = type_vocab_size _A = layer_norm_eps _A = use_cache _A = rescale_embeddings _A = attention_type _A = use_bias _A = block_size _A = num_random_blocks _A = classifier_dropout class lowercase_ ( UpperCamelCase_ ): '''simple docstring''' @property def lowerCAmelCase_ ( self : List[Any] ): if self.task == "multiple-choice": _A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
7
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
0
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def __a ( A__ , A__ , A__ ) -> Dict: lowerCAmelCase = 0 if start < end: lowerCAmelCase = randint(A__ , A__ ) lowerCAmelCase = a[end] lowerCAmelCase = a[pivot] lowerCAmelCase = temp lowerCAmelCase , lowerCAmelCase = _in_place_partition(A__ , A__ , A__ ) count += _in_place_quick_sort(A__ , A__ , p - 1 ) count += _in_place_quick_sort(A__ , p + 1 , A__ ) return count def __a ( A__ , A__ , A__ ) -> Dict: lowerCAmelCase = 0 lowerCAmelCase = randint(A__ , A__ ) lowerCAmelCase = a[end] lowerCAmelCase = a[pivot] lowerCAmelCase = temp lowerCAmelCase = start - 1 for index in range(A__ , A__ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCAmelCase = new_pivot_index + 1 lowerCAmelCase = a[new_pivot_index] lowerCAmelCase = a[index] lowerCAmelCase = temp lowerCAmelCase = a[new_pivot_index + 1] lowerCAmelCase = a[end] lowerCAmelCase = temp return new_pivot_index + 1, count lowercase : Tuple = TemporaryFile() lowercase : str = 1_0_0 # 1000 elements are to be sorted lowercase , lowercase : Dict = 0, 1 # mean and standard deviation lowercase : Optional[Any] = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array lowercase : str = np.load(outfile) lowercase : Any = len(M) - 1 lowercase : Tuple = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
159
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : List[str]=1_3 , SCREAMING_SNAKE_CASE : Optional[Any]=7 , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : List[Any]=True , SCREAMING_SNAKE_CASE : Union[str, Any]=True , SCREAMING_SNAKE_CASE : Optional[int]=True , SCREAMING_SNAKE_CASE : Optional[int]=9_9 , SCREAMING_SNAKE_CASE : Dict=3_2 , SCREAMING_SNAKE_CASE : Dict=5 , SCREAMING_SNAKE_CASE : Optional[int]=4 , SCREAMING_SNAKE_CASE : Optional[Any]=3_7 , SCREAMING_SNAKE_CASE : int="gelu" , SCREAMING_SNAKE_CASE : Any=0.1 , SCREAMING_SNAKE_CASE : int=0.1 , SCREAMING_SNAKE_CASE : Dict=5_1_2 , SCREAMING_SNAKE_CASE : Union[str, Any]=1_6 , SCREAMING_SNAKE_CASE : Dict=2 , SCREAMING_SNAKE_CASE : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE : Optional[int]=4 , ) -> Optional[int]: """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = seq_length lowerCAmelCase = is_training lowerCAmelCase = use_attention_mask lowerCAmelCase = use_token_type_ids lowerCAmelCase = use_labels lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = num_choices def __A ( self : List[str] ) -> List[str]: """simple docstring""" lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase = None if self.use_attention_mask: lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase = None if self.use_token_type_ids: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __A ( self : Optional[int] ) -> Dict: """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = config_and_inputs lowerCAmelCase = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def __A ( self : List[Any] ) -> Any: """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = config_and_inputs lowerCAmelCase = True lowerCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" lowerCAmelCase = True lowerCAmelCase = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def __A ( self : Union[str, Any] ) -> Any: """simple docstring""" lowerCAmelCase = FlaxRobertaModelTester(self ) @slow def __A ( self : str ) -> Optional[Any]: """simple docstring""" for model_class_name in self.all_model_classes: lowerCAmelCase = model_class_name.from_pretrained("roberta-base" , from_pt=SCREAMING_SNAKE_CASE ) lowerCAmelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE )
159
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def __magic_name__ ( _lowerCamelCase: str=None ) -> int: '''simple docstring''' if subparsers is not None: lowerCAmelCase = subparsers.add_parser('''env''' ) else: lowerCAmelCase = argparse.ArgumentParser('''Accelerate env command''' ) parser.add_argument( '''--config_file''', default=_lowerCamelCase, help='''The config file to use for the default values in the launching script.''' ) if subparsers is not None: parser.set_defaults(func=_lowerCamelCase ) return parser def __magic_name__ ( _lowerCamelCase: int ) -> List[Any]: '''simple docstring''' lowerCAmelCase = torch.__version__ lowerCAmelCase = torch.cuda.is_available() lowerCAmelCase = is_xpu_available() lowerCAmelCase = is_npu_available() lowerCAmelCase = '''Not found''' # Get the default from the config file. if args.config_file is not None or os.path.isfile(_lowerCamelCase ): lowerCAmelCase = load_config_from_file(args.config_file ).to_dict() lowerCAmelCase = { '''`Accelerate` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Numpy version''': np.__version__, '''PyTorch version (GPU?)''': F"""{pt_version} ({pt_cuda_available})""", '''PyTorch XPU available''': str(_lowerCamelCase ), '''PyTorch NPU available''': str(_lowerCamelCase ), '''System RAM''': F"""{psutil.virtual_memory().total / 1_024 ** 3:.2f} GB""", } if pt_cuda_available: lowerCAmelCase = torch.cuda.get_device_name() print('''\nCopy-and-paste the text below in your GitHub issue\n''' ) print('''\n'''.join([F"""- {prop}: {val}""" for prop, val in info.items()] ) ) print('''- `Accelerate` default config:''' if args.config_file is None else '''- `Accelerate` config passed:''' ) lowerCAmelCase = ( '''\n'''.join([F"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else F"""\t{accelerate_config}""" ) print(_lowerCamelCase ) lowerCAmelCase = accelerate_config return info def __magic_name__ ( ) -> int: '''simple docstring''' lowerCAmelCase = env_command_parser() lowerCAmelCase = parser.parse_args() env_command(_lowerCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
535
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase ( lowercase__ ): lowercase = ['''image_processor''', '''tokenizer'''] lowercase = '''CLIPImageProcessor''' lowercase = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''') def __init__(self : Union[str, Any] ,SCREAMING_SNAKE_CASE_ : int=None ,SCREAMING_SNAKE_CASE_ : str=None ,**SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> int: """simple docstring""" lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,SCREAMING_SNAKE_CASE_ ,) lowerCAmelCase = kwargs.pop('''feature_extractor''' ) lowerCAmelCase = 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__(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) def __call__(self : Union[str, Any] ,SCREAMING_SNAKE_CASE_ : List[str]=None ,SCREAMING_SNAKE_CASE_ : Optional[int]=None ,SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ,**SCREAMING_SNAKE_CASE_ : Any ) -> List[Any]: """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: lowerCAmelCase = self.tokenizer(SCREAMING_SNAKE_CASE_ ,return_tensors=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) if images is not None: lowerCAmelCase = self.image_processor(SCREAMING_SNAKE_CASE_ ,return_tensors=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) if text is not None and images is not None: lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_ ) ,tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : List[str] ,*SCREAMING_SNAKE_CASE_ : Union[str, Any] ,**SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : Union[str, Any] ,*SCREAMING_SNAKE_CASE_ : int ,**SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Any: """simple docstring""" return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase (self : List[Any] ) -> Dict: """simple docstring""" lowerCAmelCase = self.tokenizer.model_input_names lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
535
1
"""simple docstring""" 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 __lowerCamelCase :int = logging.get_logger(__name__) __lowerCamelCase :Optional[Any] = { '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 A__ ( __lowercase): """simple docstring""" snake_case__ : str ='''detr''' snake_case__ : List[str] =['''past_key_values'''] snake_case__ : str ={ '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self: Optional[int] , __a: Tuple=True , __a: List[Any]=None , __a: List[str]=3 , __a: Any=100 , __a: Union[str, Any]=6 , __a: Union[str, Any]=2_048 , __a: str=8 , __a: Dict=6 , __a: Tuple=2_048 , __a: Optional[int]=8 , __a: int=0.0 , __a: Union[str, Any]=0.0 , __a: Optional[Any]=True , __a: Union[str, Any]="relu" , __a: str=256 , __a: int=0.1 , __a: List[str]=0.0 , __a: Union[str, Any]=0.0 , __a: int=0.02 , __a: Union[str, Any]=1.0 , __a: str=False , __a: int="sine" , __a: List[str]="resnet50" , __a: List[Any]=True , __a: Tuple=False , __a: Dict=1 , __a: Optional[Any]=5 , __a: Optional[int]=2 , __a: List[str]=1 , __a: int=1 , __a: str=5 , __a: List[Any]=2 , __a: Union[str, Any]=0.1 , **__a: Union[str, Any] , )-> int: 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.""" ) lowerCamelCase : int = CONFIG_MAPPING["resnet"](out_features=["""stage4"""] ) elif isinstance(__A , __A ): lowerCamelCase : Union[str, Any] = backbone_config.get("""model_type""" ) lowerCamelCase : Optional[Any] = CONFIG_MAPPING[backbone_model_type] lowerCamelCase : Optional[int] = config_class.from_dict(__A ) # set timm attributes to None lowerCamelCase : List[Any] = None, None, None lowerCamelCase : Tuple = use_timm_backbone lowerCamelCase : Dict = backbone_config lowerCamelCase : List[Any] = num_channels lowerCamelCase : Union[str, Any] = num_queries lowerCamelCase : Optional[Any] = d_model lowerCamelCase : Any = encoder_ffn_dim lowerCamelCase : Optional[Any] = encoder_layers lowerCamelCase : int = encoder_attention_heads lowerCamelCase : Union[str, Any] = decoder_ffn_dim lowerCamelCase : Dict = decoder_layers lowerCamelCase : Dict = decoder_attention_heads lowerCamelCase : Optional[Any] = dropout lowerCamelCase : Tuple = attention_dropout lowerCamelCase : Union[str, Any] = activation_dropout lowerCamelCase : List[Any] = activation_function lowerCamelCase : str = init_std lowerCamelCase : Dict = init_xavier_std lowerCamelCase : Tuple = encoder_layerdrop lowerCamelCase : List[str] = decoder_layerdrop lowerCamelCase : Optional[int] = encoder_layers lowerCamelCase : List[str] = auxiliary_loss lowerCamelCase : Optional[int] = position_embedding_type lowerCamelCase : Union[str, Any] = backbone lowerCamelCase : str = use_pretrained_backbone lowerCamelCase : Union[str, Any] = dilation # Hungarian matcher lowerCamelCase : Any = class_cost lowerCamelCase : int = bbox_cost lowerCamelCase : Tuple = giou_cost # Loss coefficients lowerCamelCase : Union[str, Any] = mask_loss_coefficient lowerCamelCase : Tuple = dice_loss_coefficient lowerCamelCase : str = bbox_loss_coefficient lowerCamelCase : Dict = giou_loss_coefficient lowerCamelCase : Any = eos_coefficient super().__init__(is_encoder_decoder=__A , **__A ) @property def a__ ( self: Tuple )-> int: return self.encoder_attention_heads @property def a__ ( self: str )-> Union[str, Any]: return self.d_model @classmethod def a__ ( cls: str , __a: PretrainedConfig , **__a: Optional[Any] )-> List[Any]: return cls(backbone_config=__A , **__A ) def a__ ( self: Optional[Any] )-> str: lowerCamelCase : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: lowerCamelCase : List[Any] = self.backbone_config.to_dict() lowerCamelCase : List[str] = self.__class__.model_type return output class A__ ( __lowercase): """simple docstring""" snake_case__ : str =version.parse('''1.11''') @property def a__ ( self: Union[str, Any] )-> str: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def a__ ( self: Union[str, Any] )-> Union[str, Any]: return 1e-5 @property def a__ ( self: Optional[int] )-> List[str]: return 12
711
"""simple docstring""" import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_multi_gpu class A__ ( nn.Module): """simple docstring""" def __init__( self: Dict )-> Dict: super().__init__() lowerCamelCase : Tuple = nn.Linear(3 , 4 ) lowerCamelCase : Optional[Any] = nn.BatchNormad(4 ) lowerCamelCase : Optional[Any] = nn.Linear(4 , 5 ) def a__ ( self: List[str] , __a: List[Any] )-> Optional[Any]: return self.lineara(self.batchnorm(self.lineara(__a ) ) ) class A__ ( __lowercase): """simple docstring""" def a__ ( self: Tuple , __a: int , *__a: Any , **__a: Tuple )-> Tuple: return (args[0] + 1,) + args[1:], kwargs class A__ ( __lowercase): """simple docstring""" def a__ ( self: Optional[int] , __a: List[str] , __a: List[Any] )-> List[str]: return output + 1 class A__ ( unittest.TestCase): """simple docstring""" def a__ ( self: int )-> str: lowerCamelCase : List[str] = ModelForTest() lowerCamelCase : Dict = ModelHook() add_hook_to_module(__a , __a ) self.assertEqual(test_model._hf_hook , __a ) self.assertTrue(hasattr(__a , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__a ) self.assertFalse(hasattr(__a , """_hf_hook""" ) ) self.assertFalse(hasattr(__a , """_old_forward""" ) ) def a__ ( self: int )-> str: lowerCamelCase : List[str] = ModelForTest() lowerCamelCase : Union[str, Any] = ModelHook() add_hook_to_module(__a , __a ) add_hook_to_module(__a , __a , append=__a ) self.assertEqual(isinstance(test_model._hf_hook , __a ) , __a ) self.assertEqual(len(test_model._hf_hook.hooks ) , 2 ) self.assertTrue(hasattr(__a , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__a ) self.assertFalse(hasattr(__a , """_hf_hook""" ) ) self.assertFalse(hasattr(__a , """_old_forward""" ) ) def a__ ( self: List[Any] )-> List[str]: lowerCamelCase : str = ModelForTest() lowerCamelCase : Dict = torch.randn(2 , 3 ) lowerCamelCase : Union[str, Any] = test_model(x + 1 ) lowerCamelCase : Optional[int] = test_model(x + 2 ) lowerCamelCase : List[Any] = PreForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Optional[int] = test_model(__a ) self.assertTrue(torch.allclose(__a , __a , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain lowerCamelCase : Dict = PreForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Tuple = test_model(__a ) self.assertTrue(torch.allclose(__a , __a , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks lowerCamelCase : Any = SequentialHook(PreForwardHook() , PreForwardHook() ) add_hook_to_module(__a , __a ) lowerCamelCase : Optional[Any] = test_model(__a ) assert torch.allclose(__a , __a , atol=1e-5 ) def a__ ( self: Any )-> Optional[int]: lowerCamelCase : str = ModelForTest() lowerCamelCase : List[str] = torch.randn(2 , 3 ) lowerCamelCase : int = test_model(__a ) lowerCamelCase : Dict = PostForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Tuple = test_model(__a ) self.assertTrue(torch.allclose(__a , output + 1 , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain lowerCamelCase : str = PostForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : Optional[Any] = test_model(__a ) self.assertTrue(torch.allclose(__a , output + 1 , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks lowerCamelCase : Union[str, Any] = SequentialHook(PostForwardHook() , PostForwardHook() ) add_hook_to_module(__a , __a ) lowerCamelCase : str = test_model(__a ) assert torch.allclose(__a , output + 2 , atol=1e-5 ) def a__ ( self: int )-> Dict: lowerCamelCase : List[Any] = ModelForTest() lowerCamelCase : Optional[int] = torch.randn(2 , 3 ) lowerCamelCase : List[str] = test_model(__a ) lowerCamelCase : Any = PostForwardHook() add_hook_to_module(__a , __a ) lowerCamelCase : str = test_model(__a ) self.assertTrue(torch.allclose(__a , output + 1 ) ) self.assertTrue(outputa.requires_grad ) lowerCamelCase : Optional[int] = True lowerCamelCase : Optional[int] = test_model(__a ) self.assertFalse(outputa.requires_grad ) @require_multi_gpu def a__ ( self: List[str] )-> Union[str, Any]: lowerCamelCase : int = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=1 ) ) self.assertEqual(model.lineara.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device(0 ) ) self.assertEqual(model.lineara.weight.device , torch.device(1 ) ) # We can still make a forward pass. The input does not need to be on any particular device lowerCamelCase : str = torch.randn(2 , 3 ) lowerCamelCase : Dict = model(__a ) self.assertEqual(output.device , torch.device(1 ) ) # We can add a general hook to put back output on same device as input. add_hook_to_module(__a , AlignDevicesHook(io_same_device=__a ) ) lowerCamelCase : Optional[int] = torch.randn(2 , 3 ).to(0 ) lowerCamelCase : str = model(__a ) self.assertEqual(output.device , torch.device(0 ) ) def a__ ( self: List[str] )-> Tuple: lowerCamelCase : Union[str, Any] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices lowerCamelCase : Tuple = {"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True} add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__a ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device lowerCamelCase : List[Any] = torch.device(hook_kwargs["""execution_device"""] ) self.assertEqual(model.batchnorm.running_mean.device , __a ) lowerCamelCase : Optional[Any] = torch.randn(2 , 3 ) lowerCamelCase : Optional[Any] = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload lowerCamelCase : Any = { """execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True, """offload_buffers""": True, } add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__a ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__a ) ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) lowerCamelCase : int = torch.randn(2 , 3 ) lowerCamelCase : Optional[int] = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def a__ ( self: Any )-> List[str]: lowerCamelCase : int = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices lowerCamelCase : int = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook(__a , execution_device=__a , offload=__a ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device lowerCamelCase : List[Any] = torch.device(__a ) self.assertEqual(model.batchnorm.running_mean.device , __a ) lowerCamelCase : Dict = torch.randn(2 , 3 ) lowerCamelCase : Optional[Any] = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook(__a , execution_device=__a , offload=__a , offload_buffers=__a ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) lowerCamelCase : Optional[int] = torch.randn(2 , 3 ) lowerCamelCase : int = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def a__ ( self: Optional[Any] )-> List[Any]: lowerCamelCase : List[Any] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices lowerCamelCase : Any = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook( __a , execution_device=__a , offload=__a , weights_map=model.state_dict() ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device lowerCamelCase : List[Any] = torch.device(__a ) self.assertEqual(model.batchnorm.running_mean.device , __a ) lowerCamelCase : Dict = torch.randn(2 , 3 ) lowerCamelCase : int = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook( __a , execution_device=__a , offload=__a , weights_map=model.state_dict() , offload_buffers=__a , ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) lowerCamelCase : Tuple = torch.randn(2 , 3 ) lowerCamelCase : Any = model(__a ) self.assertEqual(output.device , __a ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__a ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) )
42
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase_ = logging.getLogger(__name__) def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : str ) -> Union[str, Any]: return (preds == labels).mean() @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) lowerCamelCase_ = field(metadata={'help': 'Should contain the data files for the task.'} ) lowerCamelCase_ = field( default=1_28 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) lowerCamelCase_ = field( default=lowercase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def _lowerCAmelCase ( ) -> int: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase : Dict =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase , lowercase , lowercase : List[Any] =parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , __magic_name__ ) # Set seed set_seed(training_args.seed ) try: lowercase : Any =processors[data_args.task_name]() lowercase : Optional[int] =processor.get_labels() lowercase : str =len(__magic_name__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase : List[str] =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) lowercase : int =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowercase : Any =AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) # Get datasets lowercase : int =( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowercase : Union[str, Any] =( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__magic_name__ : EvalPrediction ) -> Dict: lowercase : Dict =np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__magic_name__ , p.label_ids )} # Data collator lowercase : List[str] =DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowercase : Dict =Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , compute_metrics=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowercase : Optional[Any] ={} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowercase : List[Any] =trainer.evaluate() lowercase : Any =os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(__magic_name__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , __magic_name__ , __magic_name__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__magic_name__ ) return results def _lowerCAmelCase ( __magic_name__ : Any ) -> Optional[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
92
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str=13 , UpperCAmelCase__ : Tuple=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[Any]=99 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : Optional[Any]=36 , UpperCAmelCase__ : str=6 , UpperCAmelCase__ : Any=6 , UpperCAmelCase__ : Optional[int]=6 , UpperCAmelCase__ : Any=37 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : List[str]=512 , UpperCAmelCase__ : List[str]=16 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Tuple=None , ): '''simple docstring''' lowercase : str =parent lowercase : int =batch_size lowercase : Any =seq_length lowercase : int =is_training lowercase : str =use_input_mask lowercase : int =use_token_type_ids lowercase : Dict =use_labels lowercase : int =vocab_size lowercase : str =embedding_size lowercase : Union[str, Any] =hidden_size lowercase : Tuple =num_hidden_layers lowercase : Any =num_hidden_groups lowercase : Union[str, Any] =num_attention_heads lowercase : Any =intermediate_size lowercase : Tuple =hidden_act lowercase : Optional[int] =hidden_dropout_prob lowercase : Union[str, Any] =attention_probs_dropout_prob lowercase : List[Any] =max_position_embeddings lowercase : int =type_vocab_size lowercase : int =type_sequence_label_size lowercase : Any =initializer_range lowercase : List[Any] =num_labels lowercase : int =num_choices lowercase : Optional[int] =scope def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : int =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase : Optional[int] =None if self.use_input_mask: lowercase : List[str] =random_attention_mask([self.batch_size, self.seq_length] ) lowercase : Dict =None if self.use_token_type_ids: lowercase : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase : Tuple =None lowercase : Any =None lowercase : Dict =None if self.use_labels: lowercase : int =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase : Optional[Any] =ids_tensor([self.batch_size] , self.num_choices ) lowercase : Any =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str ): '''simple docstring''' lowercase : int =AlbertModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) lowercase : Dict =model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) lowercase : int =model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCamelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple ): '''simple docstring''' lowercase : Tuple =AlbertForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : int =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , sentence_order_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int ): '''simple docstring''' lowercase : Tuple =AlbertForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : str =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] ): '''simple docstring''' lowercase : List[str] =AlbertForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : List[str] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ): '''simple docstring''' lowercase : Optional[Any] =self.num_labels lowercase : Any =AlbertForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : Dict =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict ): '''simple docstring''' lowercase : List[Any] =self.num_labels lowercase : str =AlbertForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] ): '''simple docstring''' lowercase : Optional[int] =self.num_choices lowercase : List[Any] =AlbertForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowercase : List[Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase : int =token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase : int =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase : List[str] =model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Union[str, Any] =self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) : Dict =config_and_inputs lowercase : Optional[Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): lowerCamelCase_ = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase_ = ( { 'feature-extraction': AlbertModel, 'fill-mask': AlbertForMaskedLM, 'question-answering': AlbertForQuestionAnswering, 'text-classification': AlbertForSequenceClassification, 'token-classification': AlbertForTokenClassification, 'zero-shot': AlbertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ = True def lowerCamelCase_ ( self : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int=False ): '''simple docstring''' lowercase : Optional[int] =super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): lowercase : Any =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) lowercase : Any =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : Tuple =AlbertModelTester(self ) lowercase : Optional[Any] =ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' lowercase : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' lowercase : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Optional[int] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase : Tuple =type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : str =AlbertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : int =AlbertModel.from_pretrained('''albert-base-v2''' ) lowercase : Optional[int] =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) lowercase : Any =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowercase : Any =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] lowercase : int =torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCAmelCase__ ) lowercase : Union[str, Any] =torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
92
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, ) __lowerCamelCase : Any = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Optional[int] = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Tuple = ['''CLIPFeatureExtractor'''] __lowerCamelCase : Dict = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Optional[Any] = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys __lowerCamelCase : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
709
from typing import Any import numpy as np def _snake_case ( lowerCAmelCase : np.ndarray ): """simple docstring""" return np.array_equal(lowerCAmelCase , matrix.conjugate().T ) def _snake_case ( lowerCAmelCase : np.ndarray , lowerCAmelCase : np.ndarray ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = v.conjugate().T SCREAMING_SNAKE_CASE_ : int = v_star.dot(lowerCAmelCase ) assert isinstance(lowerCAmelCase , np.ndarray ) return (v_star_dot.dot(lowerCAmelCase )) / (v_star.dot(lowerCAmelCase )) def _snake_case ( ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) SCREAMING_SNAKE_CASE_ : Dict = np.array([[1], [2], [3]] ) assert is_hermitian(lowerCAmelCase ), f'{a} is not hermitian.' print(rayleigh_quotient(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowerCAmelCase ), f'{a} is not hermitian.' assert rayleigh_quotient(lowerCAmelCase , lowerCAmelCase ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
316
0
'''simple docstring''' import requests __A = "" # <-- Put your OpenWeatherMap appid here! __A = "https://api.openweathermap.org/data/2.5/" def _A ( lowercase__ = "Chicago" , lowercase__ = APPID ): return requests.get(URL_BASE + """weather""" , params=locals() ).json() def _A ( lowercase__ = "Kolkata, India" , lowercase__ = APPID ): return requests.get(URL_BASE + """forecast""" , params=locals() ).json() def _A ( lowercase__ = 5_5.6_8 , lowercase__ = 1_2.5_7 , lowercase__ = APPID ): return requests.get(URL_BASE + """onecall""" , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __A = input("Enter a location:").strip() if location: pprint(current_weather(location)) else: break
325
'''simple docstring''' 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 A ( unittest.TestCase ): def A__ ( self ) -> List[str]: '''simple docstring''' lowercase__ = """hf-internal-testing/tiny-random-t5""" lowercase__ = AutoTokenizer.from_pretrained(lowerCamelCase__ ) lowercase__ = AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ) lowercase__ = tokenizer("""This is me""" , return_tensors="""pt""" ) lowercase__ = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowercase__ = model.generate(**lowerCamelCase__ ) lowercase__ = 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(lowerCamelCase__ ) lowercase__ = AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowercase__ = model_reloaded.generate(**lowerCamelCase__ ) self.assertTrue(torch.allclose(lowerCamelCase__ , lowerCamelCase__ ) ) def A__ ( self ) -> Optional[Any]: '''simple docstring''' lowercase__ = """hf-internal-testing/tiny-random-t5""" lowercase__ = AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ) lowercase__ = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(lowerCamelCase__ ): model.save_pretrained(lowerCamelCase__ ) lowercase__ = model.reverse_bettertransformer() model.save_pretrained(lowerCamelCase__ )
325
1
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(UpperCamelCase_ ) , 'Tatoeba directory does not exist.' ) class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = tempfile.mkdtemp() return TatoebaConverter(save_dir=a_ ) @slow def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" self.resolver.convert_models(['heb-eng'] ) @slow def __lowercase( self : Optional[int] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.resolver.write_model_card('opus-mt-he-en' , dry_run=a_ ) assert mmeta["long_pair"] == "heb-eng"
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class A ( UpperCAmelCase__ ): '''simple docstring''' @slow @require_torch def lowerCamelCase__ (self : int ) -> Tuple: """simple docstring""" lowercase__ = EncoderDecoderModel.from_encoder_decoder_pretrained("""prajjwal1/bert-tiny""" , """prajjwal1/bert-tiny""" ) lowercase__ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) lowercase__ = bertabert.config.encoder.vocab_size lowercase__ = tokenizer.sep_token_id lowercase__ = tokenizer.cls_token_id lowercase__ = 128 lowercase__ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""train[:1%]""" ) lowercase__ = datasets.load_dataset("""cnn_dailymail""" , """3.0.0""" , split="""validation[:1%]""" ) lowercase__ = train_dataset.select(range(32 ) ) lowercase__ = val_dataset.select(range(16 ) ) lowercase__ = 4 def _map_to_encoder_decoder_inputs(_UpperCAmelCase : Any ): # Tokenizer will automatically set [BOS] <text> [EOS] lowercase__ = tokenizer(batch["""article"""] , padding="""max_length""" , truncation=_UpperCAmelCase , max_length=512 ) lowercase__ = tokenizer(batch["""highlights"""] , padding="""max_length""" , truncation=_UpperCAmelCase , max_length=128 ) lowercase__ = inputs.input_ids lowercase__ = inputs.attention_mask lowercase__ = outputs.input_ids lowercase__ = outputs.input_ids.copy() lowercase__ = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["""labels"""] ] lowercase__ = outputs.attention_mask assert all(len(_UpperCAmelCase ) == 512 for x in inputs.input_ids ) assert all(len(_UpperCAmelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(_UpperCAmelCase : List[Any] ): lowercase__ = pred.label_ids lowercase__ = pred.predictions # all unnecessary tokens are removed lowercase__ = tokenizer.batch_decode(_UpperCAmelCase , skip_special_tokens=_UpperCAmelCase ) lowercase__ = tokenizer.batch_decode(_UpperCAmelCase , skip_special_tokens=_UpperCAmelCase ) lowercase__ = sum([int(pred_str[i] == label_str[i] ) for i in range(len(_UpperCAmelCase ) )] ) / len(_UpperCAmelCase ) return {"accuracy": accuracy} # map train dataset lowercase__ = train_dataset.map( _map_to_encoder_decoder_inputs , batched=_UpperCAmelCase , batch_size=_UpperCAmelCase , remove_columns=["""article""", """highlights"""] , ) train_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) # same for validation dataset lowercase__ = val_dataset.map( _map_to_encoder_decoder_inputs , batched=_UpperCAmelCase , batch_size=_UpperCAmelCase , remove_columns=["""article""", """highlights"""] , ) val_dataset.set_format( type="""torch""" , columns=["""input_ids""", """attention_mask""", """decoder_input_ids""", """decoder_attention_mask""", """labels"""] , ) lowercase__ = self.get_auto_remove_tmp_dir() lowercase__ = SeqaSeqTrainingArguments( output_dir=_UpperCAmelCase , per_device_train_batch_size=_UpperCAmelCase , per_device_eval_batch_size=_UpperCAmelCase , predict_with_generate=_UpperCAmelCase , evaluation_strategy="""steps""" , do_train=_UpperCAmelCase , do_eval=_UpperCAmelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer lowercase__ = SeqaSeqTrainer( model=_UpperCAmelCase , args=_UpperCAmelCase , compute_metrics=_compute_metrics , train_dataset=_UpperCAmelCase , eval_dataset=_UpperCAmelCase , tokenizer=_UpperCAmelCase , ) # start training trainer.train()
15
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() @dataclass class lowerCamelCase__ : a__ : nn.Module a__ : List[nn.Module] = field(default_factory=lowerCamelCase_ ) a__ : list = field(default_factory=lowerCamelCase_ ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case : Optional[Any] = len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE ) def __call__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE ) [x.remove() for x in self.handles] return self @property def lowerCamelCase_ ( self ): """simple docstring""" return list(filter(lambda SCREAMING_SNAKE_CASE : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCamelCase__ : a__ : nn.Module a__ : nn.Module a__ : int = 1 a__ : List = field(default_factory=lowerCamelCase_ ) a__ : List = field(default_factory=lowerCamelCase_ ) a__ : bool = True def __call__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case : List[Any] = Tracker(self.dest )(SCREAMING_SNAKE_CASE ).parametrized snake_case : Optional[int] = Tracker(self.src )(SCREAMING_SNAKE_CASE ).parametrized snake_case : List[str] = list(filter(lambda SCREAMING_SNAKE_CASE : type(SCREAMING_SNAKE_CASE ) not in self.src_skip , SCREAMING_SNAKE_CASE ) ) snake_case : Any = list(filter(lambda SCREAMING_SNAKE_CASE : type(SCREAMING_SNAKE_CASE ) not in self.dest_skip , SCREAMING_SNAKE_CASE ) ) if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE )} operations while''' F''' destination module has {len(SCREAMING_SNAKE_CASE )}.''' ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class lowerCamelCase__ ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__() snake_case : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(("conv1", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("block" ), F'''Unexpected layer name {k}''' snake_case : List[Any] = len(SCREAMING_SNAKE_CASE ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) snake_case : Union[str, Any] = nn.ModuleDict(SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE ): """simple docstring""" return get_trunk_forward_outputs( SCREAMING_SNAKE_CASE , out_feat_keys=SCREAMING_SNAKE_CASE , feature_blocks=self._feature_blocks , ) class lowerCamelCase__ ( lowerCamelCase_ ): def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case : Optional[Any] = x.split("-" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" if x not in self: snake_case : Dict = self.convert_name_to_timm(SCREAMING_SNAKE_CASE ) snake_case : Union[str, Any] = partial(lambda: (timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ).eval(), None) ) else: snake_case : int = super().__getitem__(SCREAMING_SNAKE_CASE ) return val class lowerCamelCase__ ( lowerCamelCase_ ): def __getitem__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" if "seer" in x and "in1k" not in x: snake_case : List[Any] = RegNetModel else: snake_case : Dict = RegNetForImageClassification return val def UpperCamelCase__ ( lowercase__ : str , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): for from_key, to_key in keys: snake_case : Optional[int] = from_state_dict[from_key].clone() print(F'''Copied key={from_key} to={to_key}''' ) return to_state_dict def UpperCamelCase__ ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): print(F'''Converting {name}...''' ) with torch.no_grad(): snake_case , snake_case : str = from_model_func() snake_case : Optional[int] = our_model_func(lowercase__ ).eval() snake_case : str = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) snake_case : Union[str, Any] = torch.randn((1, 3, 224, 224) ) module_transfer(lowercase__ ) if from_state_dict is not None: snake_case : Optional[int] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: snake_case : Tuple = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")] snake_case : Dict = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) snake_case : int = our_model(lowercase__ , output_hidden_states=lowercase__ ) snake_case : List[Any] = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) snake_case : List[Any] = from_model(lowercase__ ) snake_case : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: snake_case : Tuple = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add model" , use_temp_dir=lowercase__ , ) snake_case : int = 224 if "seer" not in name else 384 # we can use the convnext one snake_case : List[str] = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add image processor" , use_temp_dir=lowercase__ , ) print(F'''Pushed {name}''' ) def UpperCamelCase__ ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): snake_case : Optional[Any] = "imagenet-1k-id2label.json" snake_case : Union[str, Any] = 1000 snake_case : Any = (1, num_labels) snake_case : Optional[int] = "huggingface/label-files" snake_case : Optional[Any] = num_labels snake_case : int = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type="dataset" ) ) , "r" ) ) snake_case : int = {int(lowercase__ ): v for k, v in idalabel.items()} snake_case : Optional[int] = idalabel snake_case : List[str] = {v: k for k, v in idalabel.items()} snake_case : List[Any] = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) snake_case : Union[str, Any] = { "regnet-x-002": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="x" ), "regnet-x-004": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="x" ), "regnet-x-006": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="x" ), "regnet-x-008": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="x" ), "regnet-x-016": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="x" ), "regnet-x-032": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="x" ), "regnet-x-040": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="x" ), "regnet-x-064": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="x" ), "regnet-x-080": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="x" ), "regnet-x-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="x" ), "regnet-x-160": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="x" ), "regnet-x-320": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="x" ), # y variant "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), "regnet-y-004": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), "regnet-y-006": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), "regnet-y-008": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), "regnet-y-016": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), "regnet-y-032": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), "regnet-y-040": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), "regnet-y-064": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), "regnet-y-080": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), "regnet-y-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), "regnet-y-160": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), "regnet-y-320": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), # finetuned on imagenet "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), } snake_case : Dict = NameToOurModelFuncMap() snake_case : int = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: snake_case : Tuple = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location="cpu" ) snake_case : List[str] = model_func() # check if we have a head, if yes add it snake_case : List[str] = files["classy_state_dict"]["base_model"]["model"] snake_case : Dict = model_state_dict["trunk"] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained snake_case : int = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : Union[str, Any] = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : Optional[Any] = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) snake_case : Tuple = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned snake_case : Any = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : str = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) snake_case : str = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) snake_case : Optional[Any] = partial( lowercase__ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=6_20.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
134
0
def SCREAMING_SNAKE_CASE__ ( snake_case__ :Dict , snake_case__ :int ) -> str: print('\nThe shortest path matrix using Floyd Warshall algorithm\n' ) for i in range(snake_case__ ): for j in range(snake_case__ ): if dist[i][j] != float('inf' ): print(int(dist[i][j] ) , end='\t' ) else: print('INF' , end='\t' ) print() def SCREAMING_SNAKE_CASE__ ( snake_case__ :List[str] , snake_case__ :Dict ) -> str: _lowercase = [[float('inf' ) for _ in range(snake_case__ )] for _ in range(snake_case__ )] for i in range(snake_case__ ): for j in range(snake_case__ ): _lowercase = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(snake_case__ ): # looping through rows of graph array for i in range(snake_case__ ): # looping through columns of graph array for j in range(snake_case__ ): if ( dist[i][k] != float('inf' ) and dist[k][j] != float('inf' ) and dist[i][k] + dist[k][j] < dist[i][j] ): _lowercase = dist[i][k] + dist[k][j] _print_dist(snake_case__ , snake_case__ ) return dist, v if __name__ == "__main__": snake_case = int(input("""Enter number of vertices: """)) snake_case = int(input("""Enter number of edges: """)) snake_case = [[float("""inf""") for i in range(v)] for j in range(v)] for i in range(v): snake_case = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("""\nEdge """, i + 1) snake_case = int(input("""Enter source:""")) snake_case = int(input("""Enter destination:""")) snake_case = float(input("""Enter weight:""")) snake_case = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
535
from __future__ import annotations from collections.abc import Generator def SCREAMING_SNAKE_CASE__ ( ) -> Generator[int, None, None]: _lowercase = {} _lowercase = 2 while True: _lowercase = factor_map.pop(snake_case__ , snake_case__ ) if factor: _lowercase = factor + prime while x in factor_map: x += factor _lowercase = factor else: _lowercase = prime yield prime prime += 1 def SCREAMING_SNAKE_CASE__ ( snake_case__ :float = 1E10 ) -> int: _lowercase = sieve() _lowercase = 1 while True: _lowercase = next(snake_case__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(snake_case__ ) n += 2 if __name__ == "__main__": print(solution())
535
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = "gpt_neox_japanese" def __init__( self : List[str] , snake_case_ : Any=32_000 , snake_case_ : Optional[Any]=2_560 , snake_case_ : Optional[int]=32 , snake_case_ : str=32 , snake_case_ : Optional[Any]=4 , snake_case_ : Union[str, Any]="gelu" , snake_case_ : List[str]=1.00 , snake_case_ : Any=10_000 , snake_case_ : Union[str, Any]=2_048 , snake_case_ : Tuple=0.02 , snake_case_ : List[Any]=1E-5 , snake_case_ : Any=True , snake_case_ : Optional[Any]=31_996 , snake_case_ : Tuple=31_999 , snake_case_ : Dict=0.1 , snake_case_ : str=0.0 , **snake_case_ : Tuple , ): super().__init__(bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ ) snake_case__ : Dict = vocab_size snake_case__ : Dict = max_position_embeddings snake_case__ : Optional[Any] = hidden_size snake_case__ : Any = num_hidden_layers snake_case__ : str = num_attention_heads snake_case__ : int = intermediate_multiple_size snake_case__ : Tuple = hidden_act snake_case__ : int = rotary_pct snake_case__ : Optional[int] = rotary_emb_base snake_case__ : List[Any] = initializer_range snake_case__ : Optional[int] = layer_norm_eps snake_case__ : int = use_cache snake_case__ : Union[str, Any] = attention_dropout snake_case__ : Any = hidden_dropout
374
'''simple docstring''' def __snake_case( ) -> Optional[Any]: for n in range(1 , 1_000_000 ): yield n * (n + 1) // 2 def __snake_case( _lowerCAmelCase ) -> str: snake_case__ : Optional[int] = 1 snake_case__ : List[Any] = 2 while i * i <= n: snake_case__ : Dict = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __snake_case( ) -> List[str]: return next(i for i in triangle_number_generator() if count_divisors(_lowerCAmelCase ) > 500 ) if __name__ == "__main__": print(solution())
374
1
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _lowerCamelCase = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) _lowerCamelCase = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) _lowerCamelCase = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) _lowerCamelCase = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) _lowerCamelCase = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) _lowerCamelCase = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) _lowerCamelCase = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def __UpperCAmelCase( ): _lowerCamelCase : Optional[Any] = randrange(len(SCREAMING_SNAKE_CASE_ ) ), randrange(len(SCREAMING_SNAKE_CASE_ ) ) _lowerCamelCase : List[Any] = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] _lowerCamelCase : Optional[int] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __UpperCAmelCase( lowercase_ = 1_00 ): return (generate_random_hand() for _ in range(SCREAMING_SNAKE_CASE_ )) @pytest.mark.parametrize('''hand, expected''' , SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase( lowercase_ , lowercase_ ): assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase( lowercase_ , lowercase_ ): assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase( lowercase_ , lowercase_ , lowercase_ ): _lowerCamelCase : Optional[Any] = PokerHand(SCREAMING_SNAKE_CASE_ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase( lowercase_ , lowercase_ ): assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase( lowercase_ , lowercase_ ): assert PokerHand(SCREAMING_SNAKE_CASE_ )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , SCREAMING_SNAKE_CASE_ ) def __UpperCAmelCase( lowercase_ , lowercase_ , lowercase_ ): assert PokerHand(SCREAMING_SNAKE_CASE_ ).compare_with(PokerHand(SCREAMING_SNAKE_CASE_ ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def __UpperCAmelCase( lowercase_ , lowercase_ , lowercase_ ): assert PokerHand(SCREAMING_SNAKE_CASE_ ).compare_with(PokerHand(SCREAMING_SNAKE_CASE_ ) ) == expected def __UpperCAmelCase( ): _lowerCamelCase : Optional[Any] = [PokerHand(SCREAMING_SNAKE_CASE_ ) for hand in SORTED_HANDS] _lowerCamelCase : Optional[int] = poker_hands.copy() shuffle(SCREAMING_SNAKE_CASE_ ) _lowerCamelCase : Optional[int] = chain(sorted(SCREAMING_SNAKE_CASE_ ) ) for index, hand in enumerate(SCREAMING_SNAKE_CASE_ ): assert hand == poker_hands[index] def __UpperCAmelCase( ): _lowerCamelCase : Any = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=SCREAMING_SNAKE_CASE_ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def __UpperCAmelCase( ): _lowerCamelCase : List[Any] = PokerHand('''2C 4S AS 3D 5C''' ) _lowerCamelCase : List[Any] = True _lowerCamelCase : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __UpperCAmelCase( ): _lowerCamelCase : Dict = 0 _lowerCamelCase : List[str] = os.path.abspath(os.path.dirname(SCREAMING_SNAKE_CASE_ ) ) _lowerCamelCase : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , '''poker_hands.txt''' ) with open(SCREAMING_SNAKE_CASE_ ) as file_hand: for line in file_hand: _lowerCamelCase : str = line[:14].strip() _lowerCamelCase : Optional[int] = line[15:].strip() _lowerCamelCase : str = PokerHand(SCREAMING_SNAKE_CASE_ ), PokerHand(SCREAMING_SNAKE_CASE_ ) _lowerCamelCase : Tuple = player.compare_with(SCREAMING_SNAKE_CASE_ ) if output == "Win": answer += 1 assert answer == 3_76
702
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCamelCase = { 'configuration_roberta_prelayernorm': [ 'ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaPreLayerNormConfig', 'RobertaPreLayerNormOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaPreLayerNormForCausalLM', 'RobertaPreLayerNormForMaskedLM', 'RobertaPreLayerNormForMultipleChoice', 'RobertaPreLayerNormForQuestionAnswering', 'RobertaPreLayerNormForSequenceClassification', 'RobertaPreLayerNormForTokenClassification', 'RobertaPreLayerNormModel', 'RobertaPreLayerNormPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaPreLayerNormForCausalLM', 'TFRobertaPreLayerNormForMaskedLM', 'TFRobertaPreLayerNormForMultipleChoice', 'TFRobertaPreLayerNormForQuestionAnswering', 'TFRobertaPreLayerNormForSequenceClassification', 'TFRobertaPreLayerNormForTokenClassification', 'TFRobertaPreLayerNormMainLayer', 'TFRobertaPreLayerNormModel', 'TFRobertaPreLayerNormPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxRobertaPreLayerNormForCausalLM', 'FlaxRobertaPreLayerNormForMaskedLM', 'FlaxRobertaPreLayerNormForMultipleChoice', 'FlaxRobertaPreLayerNormForQuestionAnswering', 'FlaxRobertaPreLayerNormForSequenceClassification', 'FlaxRobertaPreLayerNormForTokenClassification', 'FlaxRobertaPreLayerNormModel', 'FlaxRobertaPreLayerNormPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, RobertaPreLayerNormOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
613
0
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __lowerCAmelCase = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) __lowerCAmelCase = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) __lowerCAmelCase = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) __lowerCAmelCase = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) __lowerCAmelCase = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 1_4]), ('2H 5D 3C AS 5S', False, [1_4, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) __lowerCAmelCase = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) __lowerCAmelCase = ( ('JH AH TH KH QH', 2_3), ('JH 9H TH KH QH', 2_2), ('JC KH JS JD JH', 2_1), ('KH KC 3S 3H 3D', 2_0), ('8C 9C 5C 3C TC', 1_9), ('JS QS 9H TS KH', 1_8), ('7C 7S KH 2H 7H', 1_7), ('3C KH 5D 5S KH', 1_6), ('QH 8H KD JH 8S', 1_5), ('2D 6D 9D TH 7D', 1_4), ) def a ( ) ->Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = randrange(len(a ) ), randrange(len(a ) ) SCREAMING_SNAKE_CASE = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def a ( a = 100 ) ->List[Any]: '''simple docstring''' return (generate_random_hand() for _ in range(a )) @pytest.mark.parametrize('''hand, expected''' , a ) def a ( a , a ) ->Optional[int]: '''simple docstring''' assert PokerHand(a )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , a ) def a ( a , a ) ->List[str]: '''simple docstring''' assert PokerHand(a )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , a ) def a ( a , a , a ) ->int: '''simple docstring''' SCREAMING_SNAKE_CASE = PokerHand(a ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , a ) def a ( a , a ) ->str: '''simple docstring''' assert PokerHand(a )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , a ) def a ( a , a ) ->Union[str, Any]: '''simple docstring''' assert PokerHand(a )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , a ) def a ( a , a , a ) ->Optional[Any]: '''simple docstring''' assert PokerHand(a ).compare_with(PokerHand(a ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def a ( a , a , a ) ->List[Any]: '''simple docstring''' assert PokerHand(a ).compare_with(PokerHand(a ) ) == expected def a ( ) ->Any: '''simple docstring''' SCREAMING_SNAKE_CASE = [PokerHand(a ) for hand in SORTED_HANDS] SCREAMING_SNAKE_CASE = poker_hands.copy() shuffle(a ) SCREAMING_SNAKE_CASE = chain(sorted(a ) ) for index, hand in enumerate(a ): assert hand == poker_hands[index] def a ( ) ->Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=a ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def a ( ) ->Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = PokerHand('''2C 4S AS 3D 5C''' ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def a ( ) ->str: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = os.path.abspath(os.path.dirname(a ) ) SCREAMING_SNAKE_CASE = os.path.join(a , '''poker_hands.txt''' ) with open(a ) as file_hand: for line in file_hand: SCREAMING_SNAKE_CASE = line[:14].strip() SCREAMING_SNAKE_CASE = line[15:].strip() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = PokerHand(a ), PokerHand(a ) SCREAMING_SNAKE_CASE = player.compare_with(a ) if output == "Win": answer += 1 assert answer == 376
201
import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def a ( a , a ) ->Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = old_name if "patch_embed" in old_name: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = old_name.split('''.''' ) if layer == "0": SCREAMING_SNAKE_CASE = old_name.replace('''0''' , '''convolution1''' ) elif layer == "1": SCREAMING_SNAKE_CASE = old_name.replace('''1''' , '''batchnorm_before''' ) elif layer == "3": SCREAMING_SNAKE_CASE = old_name.replace('''3''' , '''convolution2''' ) else: SCREAMING_SNAKE_CASE = old_name.replace('''4''' , '''batchnorm_after''' ) if "network" in old_name and re.search(r'''\d\.\d''' , a ): SCREAMING_SNAKE_CASE = r'''\b\d{2}\b''' if bool(re.search(a , a ) ): SCREAMING_SNAKE_CASE = re.search(r'''\d\.\d\d.''' , a ).group() else: SCREAMING_SNAKE_CASE = re.search(r'''\d\.\d.''' , a ).group() if int(match[0] ) < 6: SCREAMING_SNAKE_CASE = old_name.replace(a , '''''' ) SCREAMING_SNAKE_CASE = trimmed_name.replace('''network''' , match[0] + '''.meta4D_layers.blocks.''' + match[2:-1] ) SCREAMING_SNAKE_CASE = '''intermediate_stages.''' + trimmed_name else: SCREAMING_SNAKE_CASE = old_name.replace(a , '''''' ) if int(match[2] ) < num_meta4D_last_stage: SCREAMING_SNAKE_CASE = trimmed_name.replace('''network''' , '''meta4D_layers.blocks.''' + match[2] ) else: SCREAMING_SNAKE_CASE = str(int(match[2] ) - num_meta4D_last_stage ) SCREAMING_SNAKE_CASE = trimmed_name.replace('''network''' , '''meta3D_layers.blocks.''' + layer_index ) if "norm1" in old_name: SCREAMING_SNAKE_CASE = trimmed_name.replace('''norm1''' , '''layernorm1''' ) elif "norm2" in old_name: SCREAMING_SNAKE_CASE = trimmed_name.replace('''norm2''' , '''layernorm2''' ) elif "fc1" in old_name: SCREAMING_SNAKE_CASE = trimmed_name.replace('''fc1''' , '''linear_in''' ) elif "fc2" in old_name: SCREAMING_SNAKE_CASE = trimmed_name.replace('''fc2''' , '''linear_out''' ) SCREAMING_SNAKE_CASE = '''last_stage.''' + trimmed_name elif "network" in old_name and re.search(r'''.\d.''' , a ): SCREAMING_SNAKE_CASE = old_name.replace('''network''' , '''intermediate_stages''' ) if "fc" in new_name: SCREAMING_SNAKE_CASE = new_name.replace('''fc''' , '''convolution''' ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): SCREAMING_SNAKE_CASE = new_name.replace('''norm1''' , '''batchnorm_before''' ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): SCREAMING_SNAKE_CASE = new_name.replace('''norm2''' , '''batchnorm_after''' ) if "proj" in new_name: SCREAMING_SNAKE_CASE = new_name.replace('''proj''' , '''projection''' ) if "dist_head" in new_name: SCREAMING_SNAKE_CASE = new_name.replace('''dist_head''' , '''distillation_classifier''' ) elif "head" in new_name: SCREAMING_SNAKE_CASE = new_name.replace('''head''' , '''classifier''' ) elif "patch_embed" in new_name: SCREAMING_SNAKE_CASE = '''efficientformer.''' + new_name elif new_name == "norm.weight" or new_name == "norm.bias": SCREAMING_SNAKE_CASE = new_name.replace('''norm''' , '''layernorm''' ) SCREAMING_SNAKE_CASE = '''efficientformer.''' + new_name else: SCREAMING_SNAKE_CASE = '''efficientformer.encoder.''' + new_name return new_name def a ( a , a ) ->Any: '''simple docstring''' for key in checkpoint.copy().keys(): SCREAMING_SNAKE_CASE = checkpoint.pop(a ) SCREAMING_SNAKE_CASE = val return checkpoint def a ( ) ->List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE = Image.open(requests.get(a , stream=a ).raw ) return image def a ( a , a , a , a ) ->Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = torch.load(a , map_location='''cpu''' )['''model'''] SCREAMING_SNAKE_CASE = EfficientFormerConfig.from_json_file(a ) SCREAMING_SNAKE_CASE = EfficientFormerForImageClassificationWithTeacher(a ) SCREAMING_SNAKE_CASE = '''_'''.join(checkpoint_path.split('''/''' )[-1].split('''.''' )[0].split('''_''' )[:-1] ) SCREAMING_SNAKE_CASE = config.depths[-1] - config.num_metaad_blocks + 1 SCREAMING_SNAKE_CASE = convert_torch_checkpoint(a , a ) model.load_state_dict(a ) model.eval() SCREAMING_SNAKE_CASE = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } # prepare image SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = 256 SCREAMING_SNAKE_CASE = 224 SCREAMING_SNAKE_CASE = EfficientFormerImageProcessor( size={'''shortest_edge''': image_size} , crop_size={'''height''': crop_size, '''width''': crop_size} , resample=pillow_resamplings['''bicubic'''] , ) SCREAMING_SNAKE_CASE = processor(images=a , return_tensors='''pt''' ).pixel_values # original processing pipeline SCREAMING_SNAKE_CASE = Compose( [ Resize(a , interpolation=pillow_resamplings['''bicubic'''] ), CenterCrop(a ), ToTensor(), Normalize(a , a ), ] ) SCREAMING_SNAKE_CASE = image_transforms(a ).unsqueeze(0 ) assert torch.allclose(a , a ) SCREAMING_SNAKE_CASE = model(a ) SCREAMING_SNAKE_CASE = outputs.logits SCREAMING_SNAKE_CASE = (1, 1000) if "l1" in model_name: SCREAMING_SNAKE_CASE = torch.Tensor( [-0.13_12, 0.43_53, -1.04_99, -0.51_24, 0.41_83, -0.67_93, -1.37_77, -0.08_93, -0.73_58, -2.43_28] ) assert torch.allclose(logits[0, :10] , a , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: SCREAMING_SNAKE_CASE = torch.Tensor( [-1.31_50, -1.54_56, -1.25_56, -0.84_96, -0.71_27, -0.78_97, -0.97_28, -0.30_52, 0.37_51, -0.31_27] ) assert torch.allclose(logits[0, :10] , a , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: SCREAMING_SNAKE_CASE = torch.Tensor( [-1.02_83, -1.41_31, -0.56_44, -1.31_15, -0.57_85, -1.20_49, -0.75_28, 0.19_92, -0.38_22, -0.08_78] ) assert logits.shape == expected_shape else: raise ValueError( F"""Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7""" ) # Save Checkpoints Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) print(F"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) processor.save_pretrained(a ) print(F"""Processor successfuly saved at {pytorch_dump_path}""" ) if push_to_hub: print('''Pushing model to the hub...''' ) model.push_to_hub( repo_id=F"""Bearnardd/{pytorch_dump_path}""" , commit_message='''Add model''' , use_temp_dir=a , ) processor.push_to_hub( repo_id=F"""Bearnardd/{pytorch_dump_path}""" , commit_message='''Add image processor''' , use_temp_dir=a , ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) __lowerCAmelCase = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
201
1
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class _A: """simple docstring""" def __init__( self , _A , _A=2 , _A=True , _A=False , _A=10 , _A=3 , _A=32 * 4 , _A=32 * 6 , _A=4 , _A=32 , ): __A : str = parent __A : List[Any] = batch_size __A : Optional[int] = is_training __A : List[str] = use_auxiliary_loss __A : List[str] = num_queries __A : Tuple = num_channels __A : Any = min_size __A : Union[str, Any] = max_size __A : str = num_labels __A : str = mask_feature_size def UpperCAmelCase_ ( self ): __A : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _A ) __A : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_A ) __A : int = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_A ) > 0.5 ).float() __A : Tuple = (torch.rand((self.batch_size, self.num_labels) , device=_A ) > 0.5).long() __A : Union[str, Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCAmelCase_ ( self ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.prepare_config_and_inputs() __A : Dict = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def UpperCAmelCase_ ( self , _A , _A ): __A : Any = output.encoder_hidden_states __A : Union[str, Any] = output.pixel_decoder_hidden_states __A : Union[str, Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_A ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_A ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_A ) , config.decoder_config.decoder_layers ) def UpperCAmelCase_ ( self , _A , _A , _A , _A=False ): with torch.no_grad(): __A : Optional[Any] = MaskFormerModel(config=_A ) model.to(_A ) model.eval() __A : int = model(pixel_values=_A , pixel_mask=_A ) __A : List[Any] = model(_A , output_hidden_states=_A ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_A , _A ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A ): __A : int = MaskFormerForInstanceSegmentation(config=_A ) model.to(_A ) model.eval() def comm_check_on_output(_A ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __A : List[Any] = model(pixel_values=_A , pixel_mask=_A ) __A : Dict = model(_A ) comm_check_on_output(_A ) __A : List[Any] = model( pixel_values=_A , pixel_mask=_A , mask_labels=_A , class_labels=_A ) comm_check_on_output(_A ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class _A( snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () UpperCamelCase : Tuple = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) UpperCamelCase : List[Any] = False UpperCamelCase : int = False UpperCamelCase : Union[str, Any] = False UpperCamelCase : Any = False def UpperCAmelCase_ ( self ): __A : Optional[Any] = MaskFormerModelTester(self ) __A : str = ConfigTester(self , config_class=_A , has_text_modality=_A ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_A , **_A , output_hidden_states=_A ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_A ) @unittest.skip(reason='MaskFormer does not use inputs_embeds' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MaskFormer does not have a get_input_embeddings method' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MaskFormer is not a generative model' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MaskFormer does not use token embeddings' ) def UpperCAmelCase_ ( self ): pass @require_torch_multi_gpu @unittest.skip( reason='MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : Dict = model_class(_A ) __A : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A : List[Any] = [*signature.parameters.keys()] __A : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _A ) @slow def UpperCAmelCase_ ( self ): for model_name in ["facebook/maskformer-swin-small-coco"]: __A : int = MaskFormerModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = (self.model_tester.min_size,) * 2 __A : Union[str, Any] = { 'pixel_values': torch.randn((2, 3, *size) , device=_A ), 'mask_labels': torch.randn((2, 10, *size) , device=_A ), 'class_labels': torch.zeros(2 , 10 , device=_A ).long(), } __A : int = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_A ) __A : Union[str, Any] = model(**_A ) self.assertTrue(outputs.loss is not None ) def UpperCAmelCase_ ( self ): __A : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_A , **_A , output_hidden_states=_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : int = model_class(_A ).to(_A ) __A : Dict = model(**_A , output_attentions=_A ) self.assertTrue(outputs.attentions is not None ) def UpperCAmelCase_ ( self ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __A : List[Any] = self.all_model_classes[1] __A : Tuple = self.model_tester.prepare_config_and_inputs() __A : Tuple = model_class(_A ) model.to(_A ) model.train() __A : Any = model(_A , mask_labels=_A , class_labels=_A ).loss loss.backward() def UpperCAmelCase_ ( self ): # only MaskFormerForInstanceSegmentation has the loss __A : str = self.all_model_classes[1] __A : Optional[int] = self.model_tester.prepare_config_and_inputs() __A : str = True __A : int = True __A : Optional[int] = model_class(_A ) model.to(_A ) model.train() __A : str = model(_A , mask_labels=_A , class_labels=_A ) __A : int = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __A : Dict = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __A : List[str] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __A : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_A ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) UpperCAmelCase : Optional[Any] = 1E-4 def _SCREAMING_SNAKE_CASE ( ) -> Any: __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class _A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ ( self ): return ( MaskFormerImageProcessor.from_pretrained('facebook/maskformer-swin-small-coco' ) if is_vision_available() else None ) def UpperCAmelCase_ ( self ): __A : int = MaskFormerModel.from_pretrained('facebook/maskformer-swin-small-coco' ).to(_A ) __A : List[Any] = self.default_image_processor __A : List[str] = prepare_img() __A : Any = image_processor(_A , return_tensors='pt' ).to(_A ) __A : Optional[Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_A , (1, 3, 800, 1088) ) with torch.no_grad(): __A : Dict = model(**_A ) __A : List[Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_A ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _A , atol=_A ) ) __A : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_A ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _A , atol=_A ) ) __A : Tuple = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_A ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _A , atol=_A ) ) def UpperCAmelCase_ ( self ): __A : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-swin-small-coco' ) .to(_A ) .eval() ) __A : List[str] = self.default_image_processor __A : int = prepare_img() __A : str = image_processor(_A , return_tensors='pt' ).to(_A ) __A : Optional[Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_A , (1, 3, 800, 1088) ) with torch.no_grad(): __A : Optional[int] = model(**_A ) # masks_queries_logits __A : Tuple = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __A : int = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __A : Dict = torch.tensor(_A ).to(_A ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _A , atol=_A ) ) # class_queries_logits __A : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __A : Optional[int] = torch.tensor( [ [1.6_5_1_2e0_0, -5.2_5_7_2e0_0, -3.3_5_1_9e0_0], [3.6_1_6_9e-0_2, -5.9_0_2_5e0_0, -2.9_3_1_3e0_0], [1.0_7_6_6e-0_4, -7.7_6_3_0e0_0, -5.1_2_6_3e0_0], ] ).to(_A ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _A , atol=_A ) ) def UpperCAmelCase_ ( self ): __A : List[str] = ( MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-resnet101-coco-stuff' ) .to(_A ) .eval() ) __A : Optional[Any] = self.default_image_processor __A : Any = prepare_img() __A : Union[str, Any] = image_processor(_A , return_tensors='pt' ).to(_A ) __A : Optional[Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(_A , (1, 3, 800, 1088) ) with torch.no_grad(): __A : int = model(**_A ) # masks_queries_logits __A : Optional[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __A : Any = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -10.7711]] __A : Optional[Any] = torch.tensor(_A ).to(_A ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _A , atol=_A ) ) # class_queries_logits __A : Any = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __A : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_A ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _A , atol=_A ) ) def UpperCAmelCase_ ( self ): __A : List[str] = ( MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-swin-small-coco' ) .to(_A ) .eval() ) __A : Any = self.default_image_processor __A : Optional[int] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='pt' , ) __A : Optional[Any] = inputs['pixel_values'].to(_A ) __A : Any = [el.to(_A ) for el in inputs['mask_labels']] __A : Optional[Any] = [el.to(_A ) for el in inputs['class_labels']] with torch.no_grad(): __A : Optional[Any] = model(**_A ) self.assertTrue(outputs.loss is not None )
711
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
0
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class lowercase(_lowercase ): __snake_case: List[Any] = (UniPCMultistepScheduler,) __snake_case: int = (('num_inference_steps', 25),) def lowercase__ ( self , **__SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" a__ = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'solver_type': 'bh2', } config.update(**__SCREAMING_SNAKE_CASE ) return config def lowercase__ ( self , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" a__ = dict(self.forward_default_kwargs ) a__ = kwargs.pop('num_inference_steps' , __SCREAMING_SNAKE_CASE ) a__ = self.dummy_sample a__ = 0.1 * sample a__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: a__ = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals a__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__SCREAMING_SNAKE_CASE ) a__ = scheduler_class.from_pretrained(__SCREAMING_SNAKE_CASE ) new_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals a__ = dummy_past_residuals[: new_scheduler.config.solver_order] a__ , a__ = sample, sample for t in range(__SCREAMING_SNAKE_CASE , time_step + scheduler.config.solver_order + 1 ): a__ = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample a__ = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowercase__ ( self , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" a__ = dict(self.forward_default_kwargs ) a__ = kwargs.pop('num_inference_steps' , __SCREAMING_SNAKE_CASE ) a__ = self.dummy_sample a__ = 0.1 * sample a__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: a__ = self.get_scheduler_config() a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals (must be after setting timesteps) a__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__SCREAMING_SNAKE_CASE ) a__ = scheduler_class.from_pretrained(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals new_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residual (must be after setting timesteps) a__ = dummy_past_residuals[: new_scheduler.config.solver_order] a__ = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample a__ = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowercase__ ( self , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" if scheduler is None: a__ = self.scheduler_classes[0] a__ = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) a__ = self.scheduler_classes[0] a__ = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) a__ = 1_0 a__ = self.dummy_model() a__ = self.dummy_sample_deter scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): a__ = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) a__ = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample return sample def lowercase__ ( self ) -> Any: """simple docstring""" a__ = dict(self.forward_default_kwargs ) a__ = kwargs.pop('num_inference_steps' , __SCREAMING_SNAKE_CASE ) for scheduler_class in self.scheduler_classes: a__ = self.get_scheduler_config() a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) a__ = self.dummy_sample a__ = 0.1 * sample if num_inference_steps is not None and hasattr(__SCREAMING_SNAKE_CASE , 'set_timesteps' ): scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) elif num_inference_steps is not None and not hasattr(__SCREAMING_SNAKE_CASE , 'set_timesteps' ): a__ = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a__ = [residual + 0.2, residual + 0.15, residual + 0.10] a__ = dummy_past_residuals[: scheduler.config.solver_order] a__ = scheduler.timesteps[5] a__ = scheduler.timesteps[6] a__ = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample a__ = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowercase__ ( self ) -> List[str]: """simple docstring""" a__ = UniPCMultistepScheduler(**self.get_scheduler_config() ) a__ = self.full_loop(scheduler=__SCREAMING_SNAKE_CASE ) a__ = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.24_64 ) < 1e-3 a__ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) a__ = DEISMultistepScheduler.from_config(scheduler.config ) a__ = DPMSolverMultistepScheduler.from_config(scheduler.config ) a__ = UniPCMultistepScheduler.from_config(scheduler.config ) a__ = self.full_loop(scheduler=__SCREAMING_SNAKE_CASE ) a__ = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.24_64 ) < 1e-3 def lowercase__ ( self ) -> Any: """simple docstring""" for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__SCREAMING_SNAKE_CASE ) def lowercase__ ( self ) -> Tuple: """simple docstring""" self.check_over_configs(thresholding=__SCREAMING_SNAKE_CASE ) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , sample_max_value=__SCREAMING_SNAKE_CASE , solver_order=__SCREAMING_SNAKE_CASE , solver_type=__SCREAMING_SNAKE_CASE , ) def lowercase__ ( self ) -> Optional[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__SCREAMING_SNAKE_CASE ) def lowercase__ ( self ) -> Tuple: """simple docstring""" for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__SCREAMING_SNAKE_CASE , solver_type=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , ) a__ = self.full_loop( solver_order=__SCREAMING_SNAKE_CASE , solver_type=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , ) assert not torch.isnan(__SCREAMING_SNAKE_CASE ).any(), "Samples have nan numbers" def lowercase__ ( self ) -> Union[str, Any]: """simple docstring""" self.check_over_configs(lower_order_final=__SCREAMING_SNAKE_CASE ) self.check_over_configs(lower_order_final=__SCREAMING_SNAKE_CASE ) def lowercase__ ( self ) -> Any: """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=__SCREAMING_SNAKE_CASE , time_step=0 ) def lowercase__ ( self ) -> Union[str, Any]: """simple docstring""" a__ = self.full_loop() a__ = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.24_64 ) < 1e-3 def lowercase__ ( self ) -> Union[str, Any]: """simple docstring""" a__ = self.full_loop(prediction_type='v_prediction' ) a__ = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 0.10_14 ) < 1e-3 def lowercase__ ( self ) -> Optional[Any]: """simple docstring""" a__ = self.scheduler_classes[0] a__ = self.get_scheduler_config(thresholding=__SCREAMING_SNAKE_CASE , dynamic_thresholding_ratio=0 ) a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) a__ = 1_0 a__ = self.dummy_model() a__ = self.dummy_sample_deter.half() scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): a__ = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) a__ = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample assert sample.dtype == torch.floataa def lowercase__ ( self , **__SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" for scheduler_class in self.scheduler_classes: a__ = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) a__ = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
273
"""simple docstring""" from itertools import product def __magic_name__ ( UpperCamelCase : int , UpperCamelCase : int ) -> list[int]: a__ = sides_number a__ = max_face_number * dice_number a__ = [0] * (max_total + 1) a__ = 1 a__ = range(UpperCamelCase , max_face_number + 1 ) for dice_numbers in product(UpperCamelCase , repeat=UpperCamelCase ): a__ = sum(UpperCamelCase ) totals_frequencies[total] += 1 return totals_frequencies def __magic_name__ ( ) -> float: a__ = total_frequency_distribution( sides_number=4 , dice_number=9 ) a__ = total_frequency_distribution( sides_number=6 , dice_number=6 ) a__ = 0 a__ = 9 a__ = 4 * 9 a__ = 6 for peter_total in range(UpperCamelCase , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) a__ = (4**9) * (6**6) a__ = peter_wins_count / total_games_number a__ = round(UpperCamelCase , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F'''{solution() = }''')
273
1
'''simple docstring''' def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE_ :Optional[Any] = len(SCREAMING_SNAKE_CASE ) print('The following activities are selected:' ) # The first activity is always selected SCREAMING_SNAKE_CASE_ :Dict = 0 print(SCREAMING_SNAKE_CASE , end=',' ) # Consider rest of the activities for j in range(SCREAMING_SNAKE_CASE ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(SCREAMING_SNAKE_CASE , end=',' ) SCREAMING_SNAKE_CASE_ :List[str] = j if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE__ : Dict = [1, 3, 0, 5, 8, 5] SCREAMING_SNAKE_CASE__ : Optional[Any] = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
233
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = {"""vocab_file""": """sentencepiece.bpe.model"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = { """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""" ), }, } SCREAMING_SNAKE_CASE__ : Any = { """moussaKam/mbarthez""": 10_24, """moussaKam/barthez""": 10_24, """moussaKam/barthez-orangesum-title""": 10_24, } SCREAMING_SNAKE_CASE__ : int = """▁""" class __lowerCAmelCase( lowerCAmelCase__ ): __snake_case : Union[str, Any] = VOCAB_FILES_NAMES __snake_case : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __snake_case : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case : str = ['input_ids', 'attention_mask'] def __init__( self : int , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : List[str]="<s>" , SCREAMING_SNAKE_CASE : str="</s>" , SCREAMING_SNAKE_CASE : Dict="</s>" , SCREAMING_SNAKE_CASE : Any="<s>" , SCREAMING_SNAKE_CASE : Dict="<unk>" , SCREAMING_SNAKE_CASE : Any="<pad>" , SCREAMING_SNAKE_CASE : Optional[Any]="<mask>" , SCREAMING_SNAKE_CASE : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE : str , ): """simple docstring""" SCREAMING_SNAKE_CASE_ :List[Any] = AddedToken(SCREAMING_SNAKE_CASE , lstrip=SCREAMING_SNAKE_CASE , rstrip=SCREAMING_SNAKE_CASE ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else mask_token SCREAMING_SNAKE_CASE_ :Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE , eos_token=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , mask_token=SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE , ) SCREAMING_SNAKE_CASE_ :Optional[int] = vocab_file SCREAMING_SNAKE_CASE_ :List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE ) ) SCREAMING_SNAKE_CASE_ :Dict = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} SCREAMING_SNAKE_CASE_ :Optional[int] = len(self.sp_model ) - 1 SCREAMING_SNAKE_CASE_ :Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE_ :str = [self.cls_token_id] SCREAMING_SNAKE_CASE_ :str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None , SCREAMING_SNAKE_CASE : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE , token_ids_a=SCREAMING_SNAKE_CASE , already_has_special_tokens=SCREAMING_SNAKE_CASE ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE )) + [1] def _lowercase ( self : Any , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ :Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _lowercase ( self : Any ): """simple docstring""" return len(self.sp_model ) def _lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ :List[Any] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : str ): """simple docstring""" return self.sp_model.encode(SCREAMING_SNAKE_CASE , out_type=SCREAMING_SNAKE_CASE ) def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ :Any = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE ) return spm_id if spm_id else self.unk_token_id def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE ) def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Optional[int] = [] SCREAMING_SNAKE_CASE_ :Tuple = '' SCREAMING_SNAKE_CASE_ :int = 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(SCREAMING_SNAKE_CASE ) + token SCREAMING_SNAKE_CASE_ :Dict = True SCREAMING_SNAKE_CASE_ :int = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ :int = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE ) return out_string.strip() def __getstate__( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE_ :List[Any] = None return state def __setstate__( self : int , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ :List[Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): SCREAMING_SNAKE_CASE_ :List[Any] = {} SCREAMING_SNAKE_CASE_ :Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[str] = None ): """simple docstring""" if not os.path.isdir(SCREAMING_SNAKE_CASE ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE_ :int = os.path.join( SCREAMING_SNAKE_CASE , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE , 'wb' ) as fi: SCREAMING_SNAKE_CASE_ :List[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
233
1
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES a__ = '''tiny-wmt19-en-ru''' # Build # borrowed from a test a__ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] a__ = dict(zip(vocab, range(len(vocab)))) a__ = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: a__ = Path(tmpdirname) a__ = build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] a__ = build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] a__ = build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, '''w''') as fp: fp.write('''\n'''.join(merges)) a__ = FSMTTokenizer( langs=['''en''', '''ru'''], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) a__ = FSMTConfig( langs=['''ru''', '''en'''], src_vocab_size=1000, tgt_vocab_size=1000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) a__ = FSMTForConditionalGeneration(config) print(f"num of params {tiny_model.num_parameters()}") # Test a__ = tokenizer(['''Making tiny model'''], return_tensors='''pt''') a__ = tiny_model(**batch) print('''test output:''', len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
279
import argparse import hashlib # hashlib is only used inside the Test class import struct class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self : Tuple , lowerCAmelCase : Tuple ) -> Dict: """simple docstring""" __UpperCamelCase : Any = data __UpperCamelCase : List[str] = [0x6_7_4_5_2_3_0_1, 0xe_f_c_d_a_b_8_9, 0x9_8_b_a_d_c_f_e, 0x1_0_3_2_5_4_7_6, 0xc_3_d_2_e_1_f_0] @staticmethod def lowerCamelCase__ ( lowerCAmelCase : str , lowerCAmelCase : Union[str, Any] ) -> str: """simple docstring""" return ((n << b) | (n >> (32 - b))) & 0xf_f_f_f_f_f_f_f def lowerCamelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __UpperCamelCase : int = b"""\x80""" + b"""\x00""" * (63 - (len(self.data ) + 8) % 64) __UpperCamelCase : int = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) ) return padded_data def lowerCamelCase__ ( self : str ) -> str: """simple docstring""" return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : Tuple ) -> List[Any]: """simple docstring""" __UpperCamelCase : Tuple = list(struct.unpack(""">16L""" , lowerCAmelCase ) ) + [0] * 64 for i in range(16 , 80 ): __UpperCamelCase : Dict = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def lowerCamelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" __UpperCamelCase : Dict = self.padding() __UpperCamelCase : int = self.split_blocks() for block in self.blocks: __UpperCamelCase : Union[str, Any] = self.expand_block(lowerCAmelCase ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : str = self.h for i in range(0 , 80 ): if 0 <= i < 20: __UpperCamelCase : List[Any] = (b & c) | ((~b) & d) __UpperCamelCase : str = 0x5_a_8_2_7_9_9_9 elif 20 <= i < 40: __UpperCamelCase : Tuple = b ^ c ^ d __UpperCamelCase : List[Any] = 0x6_e_d_9_e_b_a_1 elif 40 <= i < 60: __UpperCamelCase : Tuple = (b & c) | (b & d) | (c & d) __UpperCamelCase : List[str] = 0x8_f_1_b_b_c_d_c elif 60 <= i < 80: __UpperCamelCase : Optional[int] = b ^ c ^ d __UpperCamelCase : Tuple = 0xc_a_6_2_c_1_d_6 __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Tuple = ( self.rotate(lowerCAmelCase , 5 ) + f + e + k + expanded_block[i] & 0xf_f_f_f_f_f_f_f, a, self.rotate(lowerCAmelCase , 30 ), c, d, ) __UpperCamelCase : List[Any] = ( self.h[0] + a & 0xf_f_f_f_f_f_f_f, self.h[1] + b & 0xf_f_f_f_f_f_f_f, self.h[2] + c & 0xf_f_f_f_f_f_f_f, self.h[3] + d & 0xf_f_f_f_f_f_f_f, self.h[4] + e & 0xf_f_f_f_f_f_f_f, ) return ("{:08x}" * 5).format(*self.h ) def A__ () -> int: __UpperCamelCase : Optional[int] = b"""Test String""" assert SHAaHash(snake_case ).final_hash() == hashlib.shaa(snake_case ).hexdigest() # noqa: S324 def A__ () -> Tuple: __UpperCamelCase : Optional[Any] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) __UpperCamelCase : List[Any] = parser.parse_args() __UpperCamelCase : List[str] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: __UpperCamelCase : Tuple = f.read() else: __UpperCamelCase : Any = bytes(snake_case , """utf-8""" ) print(SHAaHash(snake_case ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
279
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase__ ) class __a ( UpperCAmelCase__ ): SCREAMING_SNAKE_CASE__ : str = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({"image": Image()} ) SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({"labels": ClassLabel} ) SCREAMING_SNAKE_CASE__ : str = "image" SCREAMING_SNAKE_CASE__ : str = "labels" def snake_case_ ( self , a__ ): if self.label_column not in features: raise ValueError(F'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column] , a__ ): raise ValueError(F'Column {self.label_column} is not a ClassLabel.' ) _lowerCamelCase = copy.deepcopy(self ) _lowerCamelCase = self.label_schema.copy() _lowerCamelCase = features[self.label_column] _lowerCamelCase = label_schema return task_template @property def snake_case_ ( self ): return { self.image_column: "image", self.label_column: "labels", }
714
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def SCREAMING_SNAKE_CASE_ ( snake_case : Any )-> str: _lowerCamelCase = filter(lambda snake_case : p.requires_grad , model.parameters() ) _lowerCamelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params A_ : List[str] =logging.getLogger(__name__) def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[int] , snake_case : Union[str, Any] )-> Tuple: if metric == "rouge2": _lowerCamelCase = '{val_avg_rouge2:.4f}-{step_count}' elif metric == "bleu": _lowerCamelCase = '{val_avg_bleu:.4f}-{step_count}' elif metric == "em": _lowerCamelCase = '{val_avg_em:.4f}-{step_count}' else: raise NotImplementedError( f'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' ' function.' ) _lowerCamelCase = ModelCheckpoint( dirpath=snake_case , filename=snake_case , monitor=f'val_{metric}' , mode='max' , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def SCREAMING_SNAKE_CASE_ ( snake_case : Union[str, Any] , snake_case : Tuple )-> Optional[Any]: return EarlyStopping( monitor=f'val_{metric}' , mode='min' if 'loss' in metric else 'max' , patience=snake_case , verbose=snake_case , ) class __a ( pl.Callback ): def snake_case_ ( self , a__ , a__ ): _lowerCamelCase = {F'lr_group_{i}': param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(a__ ) @rank_zero_only def snake_case_ ( self , a__ , a__ , a__ , a__=True ): logger.info(F'***** {type_path} results at step {trainer.global_step:05d} *****' ) _lowerCamelCase = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']} ) # Log results _lowerCamelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": _lowerCamelCase = od / 'test_results.txt' _lowerCamelCase = od / 'test_generations.txt' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _lowerCamelCase = od / F'{type_path}_results/{trainer.global_step:05d}.txt' _lowerCamelCase = od / F'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=a__ ) generations_file.parent.mkdir(exist_ok=a__ ) with open(a__ , 'a+' ) as writer: for key in sorted(a__ ): if key in ["log", "progress_bar", "preds"]: continue _lowerCamelCase = metrics[key] if isinstance(a__ , torch.Tensor ): _lowerCamelCase = val.item() _lowerCamelCase = F'{key}: {val:.6f}\n' writer.write(a__ ) if not save_generations: return if "preds" in metrics: _lowerCamelCase = '\n'.join(metrics['preds'] ) generations_file.open('w+' ).write(a__ ) @rank_zero_only def snake_case_ ( self , a__ , a__ ): try: _lowerCamelCase = pl_module.model.model.num_parameters() except AttributeError: _lowerCamelCase = pl_module.model.num_parameters() _lowerCamelCase = count_trainable_parameters(a__ ) # mp stands for million parameters trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1e6, 'grad_mp': n_trainable_pars / 1e6} ) @rank_zero_only def snake_case_ ( self , a__ , a__ ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(a__ , a__ , 'test' ) @rank_zero_only def snake_case_ ( self , a__ , a__ ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
222
0
"""simple docstring""" A: int = tuple[float, float, float] A: int = tuple[float, float, float] def _snake_case ( UpperCamelCase : Pointad , UpperCamelCase : Pointad ): UpperCAmelCase : List[str] = end_pointa[0] - end_pointa[0] UpperCAmelCase : Optional[Any] = end_pointa[1] - end_pointa[1] UpperCAmelCase : int = end_pointa[2] - end_pointa[2] return (x, y, z) def _snake_case ( UpperCamelCase : Vectorad , UpperCamelCase : Vectorad ): UpperCAmelCase : Optional[int] = ab[1] * ac[2] - ab[2] * ac[1] # *i UpperCAmelCase : Any = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j UpperCAmelCase : Union[str, Any] = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def _snake_case ( UpperCamelCase : Vectorad , UpperCamelCase : int ): return tuple(round(UpperCamelCase , UpperCamelCase ) for x in vector ) == (0, 0, 0) def _snake_case ( UpperCamelCase : Pointad , UpperCamelCase : Pointad , UpperCamelCase : Pointad , UpperCamelCase : int = 10 ): UpperCAmelCase : Optional[int] = create_vector(UpperCamelCase , UpperCamelCase ) UpperCAmelCase : Dict = create_vector(UpperCamelCase , UpperCamelCase ) return is_zero_vector(get_ad_vectors_cross(UpperCamelCase , UpperCamelCase ) , UpperCamelCase )
160
"""simple docstring""" from __future__ import annotations def _snake_case ( UpperCamelCase : list[int] , UpperCamelCase : int ): if len(UpperCamelCase ) < k or k < 0: raise ValueError("""Invalid Input""" ) UpperCAmelCase : Optional[Any] = sum(array[:k] ) for i in range(len(UpperCamelCase ) - k ): UpperCAmelCase : str = current_sum - array[i] + array[i + k] UpperCAmelCase : Tuple = max(UpperCamelCase , UpperCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() A: str = [randint(-1_0_0_0, 1_0_0_0) for i in range(1_0_0)] A: int = randint(0, 1_1_0) print(f"""The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}""")
160
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _lowerCamelCase : @staticmethod def _lowerCAmelCase ( *UpperCamelCase : Tuple , **UpperCamelCase : Any ) -> List[Any]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class _lowerCamelCase ( unittest.TestCase ): _lowerCamelCase :Dict = MODEL_FOR_OBJECT_DETECTION_MAPPING def _lowerCAmelCase ( self : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : Dict , UpperCamelCase : List[str] ) -> Any: """simple docstring""" lowerCAmelCase__ : Tuple = ObjectDetectionPipeline(model=UpperCamelCase , image_processor=UpperCamelCase ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def _lowerCAmelCase ( self : int , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ : Dict = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(UpperCamelCase ) , 0 ) for detected_object in outputs: self.assertEqual( UpperCamelCase , { """score""": ANY(UpperCamelCase ), """label""": ANY(UpperCamelCase ), """box""": {"""xmin""": ANY(UpperCamelCase ), """ymin""": ANY(UpperCamelCase ), """xmax""": ANY(UpperCamelCase ), """ymax""": ANY(UpperCamelCase )}, } , ) import datasets lowerCAmelCase__ : Union[str, Any] = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) lowerCAmelCase__ : Union[str, Any] = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] lowerCAmelCase__ : List[str] = object_detector(UpperCamelCase , threshold=0.0 ) self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) for outputs in batch_outputs: self.assertGreater(len(UpperCamelCase ) , 0 ) for detected_object in outputs: self.assertEqual( UpperCamelCase , { """score""": ANY(UpperCamelCase ), """label""": ANY(UpperCamelCase ), """box""": {"""xmin""": ANY(UpperCamelCase ), """ymin""": ANY(UpperCamelCase ), """xmax""": ANY(UpperCamelCase ), """ymax""": ANY(UpperCamelCase )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def _lowerCAmelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass @require_torch def _lowerCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" lowerCAmelCase__ : Optional[Any] = """hf-internal-testing/tiny-detr-mobilenetsv3""" lowerCAmelCase__ : Any = AutoModelForObjectDetection.from_pretrained(UpperCamelCase ) lowerCAmelCase__ : Dict = AutoFeatureExtractor.from_pretrained(UpperCamelCase ) lowerCAmelCase__ : Optional[int] = ObjectDetectionPipeline(model=UpperCamelCase , feature_extractor=UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, ] , ) lowerCAmelCase__ : List[str] = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, ], ] , ) @require_torch @slow def _lowerCAmelCase ( self : str ) -> int: """simple docstring""" lowerCAmelCase__ : Optional[int] = """facebook/detr-resnet-50""" lowerCAmelCase__ : List[str] = AutoModelForObjectDetection.from_pretrained(UpperCamelCase ) lowerCAmelCase__ : List[Any] = AutoFeatureExtractor.from_pretrained(UpperCamelCase ) lowerCAmelCase__ : Optional[int] = ObjectDetectionPipeline(model=UpperCamelCase , feature_extractor=UpperCamelCase ) lowerCAmelCase__ : List[str] = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ] , ) lowerCAmelCase__ : List[Any] = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], ] , ) @require_torch @slow def _lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" lowerCAmelCase__ : int = """facebook/detr-resnet-50""" lowerCAmelCase__ : str = pipeline("""object-detection""" , model=UpperCamelCase ) lowerCAmelCase__ : str = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ] , ) lowerCAmelCase__ : List[Any] = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], ] , ) @require_torch @slow def _lowerCAmelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" lowerCAmelCase__ : List[Any] = 0.9985 lowerCAmelCase__ : Dict = """facebook/detr-resnet-50""" lowerCAmelCase__ : List[Any] = pipeline("""object-detection""" , model=UpperCamelCase ) lowerCAmelCase__ : Dict = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=UpperCamelCase ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ] , ) @require_torch @require_pytesseract @slow def _lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" lowerCAmelCase__ : Dict = """Narsil/layoutlmv3-finetuned-funsd""" lowerCAmelCase__ : Union[str, Any] = 0.9993 lowerCAmelCase__ : Union[str, Any] = pipeline("""object-detection""" , model=UpperCamelCase , threshold=UpperCamelCase ) lowerCAmelCase__ : List[Any] = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(UpperCamelCase , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_94, """ymin""": 2_54, """xmax""": 3_43, """ymax""": 2_64}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_94, """ymin""": 2_54, """xmax""": 3_43, """ymax""": 2_64}}, ] , )
507
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _lowerCamelCase ( unittest.TestCase ): def _lowerCAmelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" lowerCAmelCase__ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCAmelCase__ : Optional[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowerCAmelCase__ : List[str] = test_metrics @require_cpu def _lowerCAmelCase ( self : int ) -> List[str]: """simple docstring""" debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _lowerCAmelCase ( self : int ) -> int: """simple docstring""" debug_launcher(self.test_metrics.main ) @require_single_gpu def _lowerCAmelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" self.test_metrics.main() @require_multi_gpu def _lowerCAmelCase ( self : Tuple ) -> int: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowerCAmelCase__ : str = ["""torchrun""", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCamelCase , env=os.environ.copy() )
507
1
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[Any]: print("\nThe shortest path matrix using Floyd Warshall algorithm\n" ) for i in range(__SCREAMING_SNAKE_CASE ): for j in range(__SCREAMING_SNAKE_CASE ): if dist[i][j] != float("inf" ): print(int(dist[i][j] ) , end="\t" ) else: print("INF" , end="\t" ) print() def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Tuple: __lowerCAmelCase: Tuple = [[float("inf" ) for _ in range(__SCREAMING_SNAKE_CASE )] for _ in range(__SCREAMING_SNAKE_CASE )] for i in range(__SCREAMING_SNAKE_CASE ): for j in range(__SCREAMING_SNAKE_CASE ): __lowerCAmelCase: Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(__SCREAMING_SNAKE_CASE ): # looping through rows of graph array for i in range(__SCREAMING_SNAKE_CASE ): # looping through columns of graph array for j in range(__SCREAMING_SNAKE_CASE ): if ( dist[i][k] != float("inf" ) and dist[k][j] != float("inf" ) and dist[i][k] + dist[k][j] < dist[i][j] ): __lowerCAmelCase: Optional[Any] = dist[i][k] + dist[k][j] _print_dist(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return dist, v if __name__ == "__main__": __A = int(input("Enter number of vertices: ")) __A = int(input("Enter number of edges: ")) __A = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): __A = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) __A = int(input("Enter source:")) __A = int(input("Enter destination:")) __A = float(input("Enter weight:")) __A = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
346
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_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( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) __A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def a__ ( __SCREAMING_SNAKE_CASE ) -> Optional[Any]: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: __lowerCAmelCase: Optional[Any] = model_type_to_module_name(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Optional[int] = importlib.import_module(F".{module_name}" , "transformers.models" ) try: return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_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. __lowerCAmelCase: Union[str, Any] = importlib.import_module("transformers" ) if hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return None def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , **__SCREAMING_SNAKE_CASE , ) -> Optional[int]: __lowerCAmelCase: Optional[Any] = 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 feature extractor 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 snake_case : def __init__( self : List[Any])-> Dict: '''simple docstring''' raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.") @classmethod @replace_list_option_in_docstrings(UpperCamelCase__) def lowercase_ ( cls : List[str] , UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[int])-> int: '''simple docstring''' __lowerCAmelCase: Optional[int] = kwargs.pop("config" , UpperCamelCase__) __lowerCAmelCase: Any = kwargs.pop("trust_remote_code" , UpperCamelCase__) __lowerCAmelCase: Dict = True __lowerCAmelCase , __lowerCAmelCase: List[Any] = FeatureExtractionMixin.get_feature_extractor_dict(UpperCamelCase__ , **UpperCamelCase__) __lowerCAmelCase: str = config_dict.get("feature_extractor_type" , UpperCamelCase__) __lowerCAmelCase: Optional[Any] = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {}): __lowerCAmelCase: Dict = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(UpperCamelCase__ , UpperCamelCase__): __lowerCAmelCase: Optional[int] = AutoConfig.from_pretrained(UpperCamelCase__ , **UpperCamelCase__) # It could be in `config.feature_extractor_type`` __lowerCAmelCase: List[Any] = getattr(UpperCamelCase__ , "feature_extractor_type" , UpperCamelCase__) if hasattr(UpperCamelCase__ , "auto_map") and "AutoFeatureExtractor" in config.auto_map: __lowerCAmelCase: Union[str, Any] = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: __lowerCAmelCase: List[str] = feature_extractor_class_from_name(UpperCamelCase__) __lowerCAmelCase: Optional[Any] = feature_extractor_auto_map is not None __lowerCAmelCase: Union[str, Any] = feature_extractor_class is not None or type(UpperCamelCase__) in FEATURE_EXTRACTOR_MAPPING __lowerCAmelCase: Optional[Any] = resolve_trust_remote_code( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__) if has_remote_code and trust_remote_code: __lowerCAmelCase: List[str] = get_class_from_dynamic_module( UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__) __lowerCAmelCase: Any = kwargs.pop("code_revision" , UpperCamelCase__) if os.path.isdir(UpperCamelCase__): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(UpperCamelCase__ , **UpperCamelCase__) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(UpperCamelCase__ , **UpperCamelCase__) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(UpperCamelCase__) in FEATURE_EXTRACTOR_MAPPING: __lowerCAmelCase: Tuple = FEATURE_EXTRACTOR_MAPPING[type(UpperCamelCase__)] return feature_extractor_class.from_dict(UpperCamelCase__ , **UpperCamelCase__) raise ValueError( f"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a " f"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following " f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys())}") @staticmethod def lowercase_ ( UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int])-> Tuple: '''simple docstring''' FEATURE_EXTRACTOR_MAPPING.register(UpperCamelCase__ , UpperCamelCase__)
346
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin __a : int = False @skip_mps class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE =StableDiffusionAttendAndExcitePipeline _SCREAMING_SNAKE_CASE =False _SCREAMING_SNAKE_CASE =TEXT_TO_IMAGE_PARAMS _SCREAMING_SNAKE_CASE =TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'} ) _SCREAMING_SNAKE_CASE =TEXT_TO_IMAGE_IMAGE_PARAMS _SCREAMING_SNAKE_CASE =TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def lowercase ( cls: List[str] ): '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(__A ) @classmethod def lowercase ( cls: str ): '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(__A ) def lowercase ( self: Any ): '''simple docstring''' torch.manual_seed(0 ) a__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__A , ) a__ = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=__A , set_alpha_to_one=__A , ) torch.manual_seed(0 ) a__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) a__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) a__ = CLIPTextModel(__A ) a__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) a__ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def lowercase ( self: int , __A: List[Any] , __A: int=0 ): '''simple docstring''' if str(__A ).startswith('''mps''' ): a__ = torch.manual_seed(__A ) else: a__ = torch.Generator(device=__A ).manual_seed(__A ) a__ = a__ = { '''prompt''': '''a cat and a frog''', '''token_indices''': [2, 5], '''generator''': generator, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', '''max_iter_to_alter''': 2, '''thresholds''': {0: 0.7}, } return inputs def lowercase ( self: List[Any] ): '''simple docstring''' a__ = '''cpu''' a__ = self.get_dummy_components() a__ = self.pipeline_class(**__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) a__ = self.get_dummy_inputs(__A ) a__ = pipe(**__A ).images a__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3) ) a__ = np.array( [0.6_3_9_0_5_3_6_4, 0.6_2_8_9_7_3_0_7, 0.4_8_5_9_9_0_1_7, 0.5_1_3_3_6_2_4, 0.5_5_5_0_0_4_8, 0.4_5_7_6_9_5_1_6, 0.5_0_3_2_6_9_7_3, 0.5_0_2_3_1_3_9, 0.4_5_3_8_4_4_9_6] ) a__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__A , 1e-3 ) def lowercase ( self: Tuple ): '''simple docstring''' super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 ) def lowercase ( self: Any ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowercase ( self: Optional[Any] ): '''simple docstring''' self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 ) def lowercase ( self: Dict ): '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def lowercase ( self: Any ): '''simple docstring''' super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 ) def lowercase ( self: Union[str, Any] ): '''simple docstring''' super().test_save_load_local(expected_max_difference=5e-4 ) def lowercase ( self: Tuple ): '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=4e-4 ) @require_torch_gpu @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @classmethod def lowercase ( cls: Any ): '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(__A ) @classmethod def lowercase ( cls: int ): '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(__A ) def lowercase ( self: List[str] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self: List[str] ): '''simple docstring''' a__ = torch.manual_seed(51 ) a__ = StableDiffusionAttendAndExcitePipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , safety_checker=__A , torch_dtype=torch.floataa ) pipe.to('''cuda''' ) a__ = '''a painting of an elephant with glasses''' a__ = [5, 7] a__ = pipe( prompt=__A , token_indices=__A , guidance_scale=7.5 , generator=__A , num_inference_steps=5 , max_iter_to_alter=5 , output_type='''numpy''' , ).images[0] a__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy''' ) assert np.abs((expected_image - image).max() ) < 5e-1
200
"""simple docstring""" class _SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self: Any ): '''simple docstring''' a__ = {} def lowercase ( self: Optional[int] ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(__A , ''' -> ''' , ''' -> '''.join([str(__A ) for j in self.vertex[i]] ) ) def lowercase ( self: Union[str, Any] , __A: int , __A: int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(__A ) else: # else make a new vertex a__ = [to_vertex] def lowercase ( self: Dict ): '''simple docstring''' a__ = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(__A , __A ) def lowercase ( self: Optional[int] , __A: int , __A: list ): '''simple docstring''' a__ = True print(__A , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__A , __A ) if __name__ == "__main__": __a : Any = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
200
1
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets a = '\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n' a = '\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n' a = '\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "pearson": Pearson Correlation\n "spearmanr": Spearman Correlation\n "matthews_correlation": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)})\n {\'pearson\': 1.0, \'spearmanr\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'cola\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def a_ ( __UpperCAmelCase , __UpperCAmelCase ) -> Tuple: """simple docstring""" return float((preds == labels).mean() ) def a_ ( __UpperCAmelCase , __UpperCAmelCase ) -> str: """simple docstring""" snake_case: Optional[Any] =simple_accuracy(__UpperCAmelCase , __UpperCAmelCase ) snake_case: List[Any] =float(fa_score(y_true=__UpperCAmelCase , y_pred=__UpperCAmelCase ) ) return { "accuracy": acc, "f1": fa, } def a_ ( __UpperCAmelCase , __UpperCAmelCase ) -> int: """simple docstring""" snake_case: Dict =float(pearsonr(__UpperCAmelCase , __UpperCAmelCase )[0] ) snake_case: Tuple =float(spearmanr(__UpperCAmelCase , __UpperCAmelCase )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def UpperCamelCase ( self : str ) -> Any: if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( 'You should supply a configuration name selected in ' '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ), 'references': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' , ) def UpperCamelCase ( self : Tuple , a_ : Union[str, Any] , a_ : List[str] ) -> Optional[int]: if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(a_ , a_ )} elif self.config_name == "stsb": return pearson_and_spearman(a_ , a_ ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(a_ , a_ ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(a_ , a_ )} else: raise KeyError( 'You should supply a configuration name selected in ' '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' )
350
'''simple docstring''' 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 a_ ( __UpperCAmelCase , __UpperCAmelCase ) -> Dict: """simple docstring""" if "xprophetnet" in prophetnet_checkpoint_path: snake_case: Optional[Any] =XLMProphetNetForConditionalGenerationOld.from_pretrained(__UpperCAmelCase ) snake_case , snake_case: str =XLMProphetNetForConditionalGeneration.from_pretrained( __UpperCAmelCase , output_loading_info=__UpperCAmelCase ) else: snake_case: Optional[int] =ProphetNetForConditionalGenerationOld.from_pretrained(__UpperCAmelCase ) snake_case , snake_case: List[str] =ProphetNetForConditionalGeneration.from_pretrained( __UpperCAmelCase , output_loading_info=__UpperCAmelCase ) snake_case: str =['key_proj', 'value_proj', 'query_proj'] snake_case: str ={ '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"]: snake_case: List[str] =key.split('.' ) if attributes[0] == "lm_head": snake_case: Dict =prophet snake_case: List[str] =prophet_old else: snake_case: Any =prophet.prophetnet snake_case: int =prophet_old.model snake_case: int =False for attribute in attributes: if attribute in mapping: snake_case: Dict =mapping[attribute] if not hasattr(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) > 0: snake_case: Optional[int] =attribute elif hasattr(__UpperCAmelCase , __UpperCAmelCase ): snake_case: Optional[Any] =attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" snake_case: Optional[Any] =old_model.weight logger.info(f'''{attribute} is initialized.''' ) snake_case: List[str] =True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" snake_case: List[Any] =old_model.bias logger.info(f'''{attribute} is initialized''' ) snake_case: List[Any] =True break elif attribute in special_keys and hasattr(__UpperCAmelCase , 'in_proj_weight' ): snake_case: Optional[int] =old_model.in_proj_weight.shape[0] // 3 snake_case: List[str] =getattr(__UpperCAmelCase , __UpperCAmelCase ) 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": snake_case: int =nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) snake_case: Any =nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": snake_case: Union[str, Any] =nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) snake_case: List[str] =nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": snake_case: List[str] =nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) snake_case: Union[str, Any] =nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) snake_case: Any =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." snake_case: Dict =nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) snake_case: Dict =True break if attribute.isdigit(): snake_case: int =model[int(__UpperCAmelCase )] snake_case: Optional[int] =old_model[int(__UpperCAmelCase )] else: snake_case: List[str] =getattr(__UpperCAmelCase , __UpperCAmelCase ) if old_attribute == "": snake_case: Union[str, Any] =old_model else: if not hasattr(__UpperCAmelCase , __UpperCAmelCase ): raise ValueError(f'''{old_model} does not have {old_attribute}''' ) snake_case: List[Any] =getattr(__UpperCAmelCase , __UpperCAmelCase ) 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(__UpperCAmelCase ) 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)
350
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __A ( UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,unittest.TestCase ): """simple docstring""" UpperCAmelCase__ = StableDiffusionInstructPixaPixPipeline UpperCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} UpperCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCAmelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __snake_case ( self): """simple docstring""" torch.manual_seed(0) _lowerCamelCase : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) _lowerCamelCase : Any = PNDMScheduler(skip_prk_steps=a__) torch.manual_seed(0) _lowerCamelCase : Optional[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : int = CLIPTextModel(a__) _lowerCamelCase : int = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''') _lowerCamelCase : List[str] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __snake_case ( self , a__ , a__=0): """simple docstring""" _lowerCamelCase : Union[str, Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__)).to(a__) _lowerCamelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1)[0] _lowerCamelCase : str = Image.fromarray(np.uinta(a__)).convert('''RGB''') if str(a__).startswith('''mps'''): _lowerCamelCase : List[str] = torch.manual_seed(a__) else: _lowerCamelCase : List[str] = torch.Generator(device=a__).manual_seed(a__) _lowerCamelCase : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """image_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def __snake_case ( self): """simple docstring""" _lowerCamelCase : Optional[Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Any = self.get_dummy_components() _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline(**a__) _lowerCamelCase : Optional[int] = sd_pipe.to(a__) sd_pipe.set_progress_bar_config(disable=a__) _lowerCamelCase : str = self.get_dummy_inputs(a__) _lowerCamelCase : List[str] = sd_pipe(**a__).images _lowerCamelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _lowerCamelCase : int = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" _lowerCamelCase : Dict = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Optional[Any] = self.get_dummy_components() _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline(**a__) _lowerCamelCase : Optional[int] = sd_pipe.to(a__) sd_pipe.set_progress_bar_config(disable=a__) _lowerCamelCase : List[str] = self.get_dummy_inputs(a__) _lowerCamelCase : Optional[Any] = """french fries""" _lowerCamelCase : List[Any] = sd_pipe(**a__ , negative_prompt=a__) _lowerCamelCase : str = output.images _lowerCamelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _lowerCamelCase : List[Any] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" _lowerCamelCase : Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : int = self.get_dummy_components() _lowerCamelCase : Optional[int] = StableDiffusionInstructPixaPixPipeline(**a__) _lowerCamelCase : Optional[int] = sd_pipe.to(a__) sd_pipe.set_progress_bar_config(disable=a__) _lowerCamelCase : Optional[Any] = self.get_dummy_inputs(a__) _lowerCamelCase : Union[str, Any] = [inputs["""prompt"""]] * 2 _lowerCamelCase : str = np.array(inputs['''image''']).astype(np.floataa) / 255.0 _lowerCamelCase : Dict = torch.from_numpy(a__).unsqueeze(0).to(a__) _lowerCamelCase : Optional[int] = image / 2 + 0.5 _lowerCamelCase : List[str] = image.permute(0 , 3 , 1 , 2) _lowerCamelCase : Optional[int] = image.repeat(2 , 1 , 1 , 1) _lowerCamelCase : int = sd_pipe(**a__).images _lowerCamelCase : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) _lowerCamelCase : Tuple = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" _lowerCamelCase : Dict = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : List[str] = self.get_dummy_components() _lowerCamelCase : List[str] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''') _lowerCamelCase : int = StableDiffusionInstructPixaPixPipeline(**a__) _lowerCamelCase : Tuple = sd_pipe.to(a__) sd_pipe.set_progress_bar_config(disable=a__) _lowerCamelCase : Dict = self.get_dummy_inputs(a__) _lowerCamelCase : Optional[int] = sd_pipe(**a__).images _lowerCamelCase : str = image[0, -3:, -3:, -1] _lowerCamelCase : List[Any] = [round(a__ , 4) for x in image_slice.flatten().tolist()] print(''','''.join([str(a__) for x in slice])) assert image.shape == (1, 32, 32, 3) _lowerCamelCase : Tuple = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3) def __snake_case ( self): """simple docstring""" _lowerCamelCase : List[Any] = self.get_dummy_components() _lowerCamelCase : Union[str, Any] = StableDiffusionInstructPixaPixPipeline(**a__) _lowerCamelCase : Union[str, Any] = VaeImageProcessor(do_resize=a__ , do_normalize=a__) _lowerCamelCase : Any = pipe.to(a__) pipe.set_progress_bar_config(disable=a__) _lowerCamelCase : Optional[int] = pipe(**self.get_dummy_inputs_by_type(a__ , input_image_type='''pt'''))[0] _lowerCamelCase : Optional[int] = components["""vae"""] _lowerCamelCase : Optional[Any] = self.get_dummy_inputs_by_type(a__ , input_image_type='''pt''') for image_param in self.image_latents_params: if image_param in inputs.keys(): _lowerCamelCase : Any = vae.encode(inputs[image_param]).latent_dist.mode() _lowerCamelCase : Optional[Any] = pipe(**a__)[0] _lowerCamelCase : int = np.abs(out - out_latents_inputs).max() self.assertLess(a__ , 1e-4 , '''passing latents as image input generate different result from passing image''') @slow @require_torch_gpu class __A ( unittest.TestCase ): """simple docstring""" def __snake_case ( self): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self , a__=0): """simple docstring""" _lowerCamelCase : Tuple = torch.manual_seed(a__) _lowerCamelCase : List[str] = load_image( '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg''') _lowerCamelCase : int = { """prompt""": """turn him into a cyborg""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """image_guidance_scale""": 1.0, """output_type""": """numpy""", } return inputs def __snake_case ( self): """simple docstring""" _lowerCamelCase : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=a__) pipe.to(a__) pipe.set_progress_bar_config(disable=a__) pipe.enable_attention_slicing() _lowerCamelCase : Dict = self.get_inputs() _lowerCamelCase : str = pipe(**a__).images _lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _lowerCamelCase : str = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=a__) _lowerCamelCase : List[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config) pipe.to(a__) pipe.set_progress_bar_config(disable=a__) pipe.enable_attention_slicing() _lowerCamelCase : List[Any] = self.get_inputs() _lowerCamelCase : Tuple = pipe(**a__).images _lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _lowerCamelCase : str = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" _lowerCamelCase : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=a__) _lowerCamelCase : Tuple = DDIMScheduler.from_config(pipe.scheduler.config) pipe.to(a__) pipe.set_progress_bar_config(disable=a__) pipe.enable_attention_slicing() _lowerCamelCase : Dict = self.get_inputs() _lowerCamelCase : Any = pipe(**a__).images _lowerCamelCase : int = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def __snake_case ( self): """simple docstring""" _lowerCamelCase : int = 0 def callback_fn(a__ , a__ , a__) -> None: _lowerCamelCase : str = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _lowerCamelCase : List[str] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) _lowerCamelCase : str = latents[0, -3:, -3:, -1] _lowerCamelCase : Tuple = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 elif step == 2: _lowerCamelCase : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) _lowerCamelCase : Union[str, Any] = latents[0, -3:, -3:, -1] _lowerCamelCase : List[str] = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 _lowerCamelCase : Any = False _lowerCamelCase : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=a__ , torch_dtype=torch.floataa) _lowerCamelCase : List[str] = pipe.to(a__) pipe.set_progress_bar_config(disable=a__) pipe.enable_attention_slicing() _lowerCamelCase : int = self.get_inputs() pipe(**a__ , callback=a__ , callback_steps=1) assert callback_fn.has_been_called assert number_of_steps == 3 def __snake_case ( self): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCamelCase : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=a__ , torch_dtype=torch.floataa) _lowerCamelCase : Union[str, Any] = pipe.to(a__) pipe.set_progress_bar_config(disable=a__) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() _lowerCamelCase : Any = self.get_inputs() _lowerCamelCase : Dict = pipe(**a__) _lowerCamelCase : Optional[int] = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __snake_case ( self): """simple docstring""" _lowerCamelCase : Optional[int] = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 _lowerCamelCase : Optional[Any] = inputs["""image"""].resize((504, 504)) _lowerCamelCase : List[str] = """timbrooks/instruct-pix2pix""" _lowerCamelCase : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a__ , safety_checker=a__ , ) pipe.to(a__) pipe.set_progress_bar_config(disable=a__) pipe.enable_attention_slicing() _lowerCamelCase : int = pipe(**a__) _lowerCamelCase : int = output.images[0] _lowerCamelCase : Optional[int] = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) _lowerCamelCase : List[str] = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-3
714
import qiskit def __UpperCAmelCase( lowercase_ = 2 ): _lowerCamelCase : Optional[Any] = qubits # Using Aer's simulator _lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('''aer_simulator''' ) # Creating a Quantum Circuit acting on the q register _lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowercase_ , lowercase_ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , lowercase_ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , lowercase_ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(lowercase_ ) ) , list(range(lowercase_ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator _lowerCamelCase : str = qiskit.execute(lowercase_ , lowercase_ , shots=10_00 ) return job.result().get_counts(lowercase_ ) if __name__ == "__main__": print(F'''Total count for various states are: {quantum_entanglement(3)}''')
613
0
'''simple docstring''' import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def _A ( A__ ): # picklable for multiprocessing """simple docstring""" return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def _A ( ): """simple docstring""" with parallel_backend('''spark''' ): assert ParallelBackendConfig.backend_name == "spark" __lowercase = [1, 2, 3] with pytest.raises(A__ ): with parallel_backend('''unsupported backend''' ): map_nested(A__ , A__ , num_proc=2 ) with pytest.raises(A__ ): with parallel_backend('''unsupported backend''' ): map_nested(A__ , A__ , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('''num_proc''' , [2, -1] ) def _A ( A__ ): """simple docstring""" __lowercase = [1, 2] __lowercase = {'''a''': 1, '''b''': 2} __lowercase = {'''a''': [1, 2], '''b''': [3, 4]} __lowercase = {'''a''': {'''1''': 1}, '''b''': 2} __lowercase = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} __lowercase = [2, 3] __lowercase = {'''a''': 2, '''b''': 3} __lowercase = {'''a''': [2, 3], '''b''': [4, 5]} __lowercase = {'''a''': {'''1''': 2}, '''b''': 3} __lowercase = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} with parallel_backend('''spark''' ): assert map_nested(A__ , A__ , num_proc=A__ ) == expected_map_nested_sa assert map_nested(A__ , A__ , num_proc=A__ ) == expected_map_nested_sa assert map_nested(A__ , A__ , num_proc=A__ ) == expected_map_nested_sa assert map_nested(A__ , A__ , num_proc=A__ ) == expected_map_nested_sa assert map_nested(A__ , A__ , num_proc=A__ ) == expected_map_nested_sa
41
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _A ( A__ ): """simple docstring""" __lowercase = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A__ , A__ ) def _A ( A__ ): """simple docstring""" __lowercase , __lowercase = emb.weight.shape __lowercase = nn.Linear(A__ , A__ , bias=A__ ) __lowercase = emb.weight.data return lin_layer def _A ( A__ , A__="facebook/mbart-large-en-ro" , A__=False , A__=False ): """simple docstring""" __lowercase = torch.load(A__ , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A__ ) __lowercase = state_dict['''encoder.embed_tokens.weight'''].shape[0] __lowercase = MBartConfig.from_pretrained(A__ , vocab_size=A__ ) if mbart_aa and finetuned: __lowercase = '''relu''' __lowercase = state_dict['''decoder.embed_tokens.weight'''] __lowercase = MBartForConditionalGeneration(A__ ) model.model.load_state_dict(A__ ) if finetuned: __lowercase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
41
1
'''simple docstring''' def lowercase__ ( __lowercase : int ) -> int: """simple docstring""" __UpperCamelCase = [[0 for _ in range(__lowercase )] for _ in range(m + 1 )] for i in range(m + 1 ): __UpperCamelCase = 1 for n in range(m + 1 ): for k in range(1 , __lowercase ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: a__ : Dict =int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: a__ : Optional[Any] =int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
434
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def lowercase__ ( __lowercase : Any , __lowercase : Union[str, Any]=False ) -> str: """simple docstring""" __UpperCamelCase = OmegaConf.load(__lowercase ) if display: print(yaml.dump(OmegaConf.to_container(__lowercase ) ) ) return config def lowercase__ ( __lowercase : Optional[int] , __lowercase : Dict=None , __lowercase : Tuple=None ) -> Union[str, Any]: """simple docstring""" if conf_path is None: __UpperCamelCase = './model_checkpoints/vqgan_only.yaml' __UpperCamelCase = load_config(__lowercase , display=__lowercase ) __UpperCamelCase = VQModel(**config.model.params ) if ckpt_path is None: __UpperCamelCase = './model_checkpoints/vqgan_only.pt' __UpperCamelCase = torch.load(__lowercase , map_location=__lowercase ) if ".ckpt" in ckpt_path: __UpperCamelCase = sd['state_dict'] model.load_state_dict(__lowercase , strict=__lowercase ) model.to(__lowercase ) del sd return model def lowercase__ ( __lowercase : int , __lowercase : int ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = model.encode(__lowercase ) print(F'''VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}''' ) __UpperCamelCase = model.decode(__lowercase ) return xrec def lowercase__ ( __lowercase : Optional[int] , __lowercase : List[Any]=False ) -> int: """simple docstring""" __UpperCamelCase , __UpperCamelCase = string.rsplit('.' , 1 ) if reload: __UpperCamelCase = importlib.import_module(__lowercase ) importlib.reload(__lowercase ) return getattr(importlib.import_module(__lowercase , package=__lowercase ) , cls ) def lowercase__ ( __lowercase : Tuple ) -> Union[str, Any]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def lowercase__ ( __lowercase : Optional[int] , __lowercase : List[Any] , __lowercase : Any=True , __lowercase : Optional[int]=True ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase = instantiate_from_config(__lowercase ) if sd is not None: model.load_state_dict(__lowercase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def lowercase__ ( __lowercase : Optional[Any] , __lowercase : Optional[Any] , __lowercase : List[str] , __lowercase : List[Any] ) -> str: """simple docstring""" if ckpt: __UpperCamelCase = torch.load(__lowercase , map_location='cpu' ) __UpperCamelCase = pl_sd['global_step'] print(F'''loaded model from global step {global_step}.''' ) else: __UpperCamelCase = {'state_dict': None} __UpperCamelCase = None __UpperCamelCase = load_model_from_config(config.model , pl_sd['state_dict'] , gpu=__lowercase , eval_mode=__lowercase )['model'] return model, global_step
434
1
def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->bool: """simple docstring""" return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(_UpperCamelCase ) ) def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) ->bool: """simple docstring""" if index == len(_UpperCamelCase ): return True # Recursive Step for i in range(_UpperCamelCase ): if valid_coloring(graph[index], _UpperCamelCase, _UpperCamelCase ): # Color current vertex lowercase : Optional[int] = i # Validate coloring if util_color(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, index + 1 ): return True # Backtrack lowercase : Optional[Any] = -1 return False def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->list[int]: """simple docstring""" lowercase : Optional[int] = [-1] * len(_UpperCamelCase ) if util_color(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, 0 ): return colored_vertices return []
319
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @require_torch def __lowerCamelCase ( self ): lowercase : Optional[Any] = pipeline( task='''zero-shot-audio-classification''' , model='''hf-internal-testing/tiny-clap-htsat-unfused''' ) lowercase : Any = load_dataset('''ashraq/esc50''' ) lowercase : Union[str, Any] = dataset['''train''']['''audio'''][-1]['''array'''] lowercase : Optional[int] = audio_classifier(SCREAMING_SNAKE_CASE__ , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'''score''': 0.501, '''label''': '''Sound of a dog'''}, {'''score''': 0.499, '''label''': '''Sound of vaccum cleaner'''}] , ) @unittest.skip('''No models are available in TF''' ) def __lowerCamelCase ( self ): pass @slow @require_torch def __lowerCamelCase ( self ): lowercase : List[str] = pipeline( task='''zero-shot-audio-classification''' , model='''laion/clap-htsat-unfused''' , ) # This is an audio of a dog lowercase : List[str] = load_dataset('''ashraq/esc50''' ) lowercase : Dict = dataset['''train''']['''audio'''][-1]['''array'''] lowercase : Dict = audio_classifier(SCREAMING_SNAKE_CASE__ , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'''score''': 0.999, '''label''': '''Sound of a dog'''}, {'''score''': 0.001, '''label''': '''Sound of vaccum cleaner'''}, ] , ) lowercase : Tuple = audio_classifier([audio] * 5 , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [ {'''score''': 0.999, '''label''': '''Sound of a dog'''}, {'''score''': 0.001, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 , ) lowercase : Dict = audio_classifier( [audio] * 5 , candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] , batch_size=5 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [ {'''score''': 0.999, '''label''': '''Sound of a dog'''}, {'''score''': 0.001, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 , ) @unittest.skip('''No models are available in TF''' ) def __lowerCamelCase ( self ): pass
319
1
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def __magic_name__( _A , _A , _A=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, f"{torch_layer} layer.weight does not match" UpperCamelCase__ = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, f"{torch_layer} layer.bias does not match" UpperCamelCase__ = nn.Parameter(lowercase_ ) def __magic_name__( _A , _A , _A ): '''simple docstring''' UpperCamelCase__ = np.asarray(weights[0] ) UpperCamelCase__ = np.asarray(weights[1] ) UpperCamelCase__ = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def __magic_name__( _A , _A , _A ): '''simple docstring''' UpperCamelCase__ = np.asarray(weights[0] ) UpperCamelCase__ = np.asarray(weights[1] ) UpperCamelCase__ = np.asarray(weights[2] ) UpperCamelCase__ = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def __magic_name__( _A , _A , _A ): '''simple docstring''' UpperCamelCase__ = weights[0][0][0] UpperCamelCase__ = np.asarray(layer_norm_a[0] ) UpperCamelCase__ = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output UpperCamelCase__ = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs UpperCamelCase__ = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: UpperCamelCase__ = intermediate_weights[2] # layernorm 2 UpperCamelCase__ = np.asarray(intermediate_weights[0][0] ) UpperCamelCase__ = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense UpperCamelCase__ = np.asarray(intermediate_weights[1][0] ) UpperCamelCase__ = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out UpperCamelCase__ = np.asarray(intermediate_weights[4][0] ) UpperCamelCase__ = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def __magic_name__( _A , _A , _A ): '''simple docstring''' UpperCamelCase__ = torch_model.reformer # word embeds UpperCamelCase__ = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): UpperCamelCase__ = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): UpperCamelCase__ = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), f"{position_embeddings[emb_idx]} emb does not match" UpperCamelCase__ = nn.Parameter(torch.tensor(lowercase_ ) ) UpperCamelCase__ = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): UpperCamelCase__ = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm UpperCamelCase__ = np.asarray(weights[7][0] ) UpperCamelCase__ = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings UpperCamelCase__ = np.asarray(weights[9][0] ) UpperCamelCase__ = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def __magic_name__( _A , _A , _A ): '''simple docstring''' UpperCamelCase__ = ReformerConfig.from_json_file(lowercase_ ) print(f"Building PyTorch model from configuration: {config}" ) UpperCamelCase__ = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , """rb""" ) as f: UpperCamelCase__ = pickle.load(lowercase_ )["weights"] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": lowerCamelCase_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer 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.''' ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
707
'''simple docstring''' from collections import defaultdict def __magic_name__( _A ): '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = True for v in tree[start]: if v not in visited: ret += dfs(_A ) if ret % 2 == 0: cuts.append(_A ) return ret def __magic_name__( ): '''simple docstring''' dfs(1 ) if __name__ == "__main__": lowerCamelCase_ , lowerCamelCase_ : int = 10, 9 lowerCamelCase_ : int = defaultdict(list) lowerCamelCase_ : dict[int, bool] = {} lowerCamelCase_ : list[int] = [] lowerCamelCase_ : Union[str, Any] = 0 lowerCamelCase_ : Tuple = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
265
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : Any , A__ : Any , A__ : List[Any] ) -> Dict: '''simple docstring''' a__ : List[Any] = dataset a__ : Tuple = process a__ : Optional[Any] = params def __len__( self : List[Any] ) -> List[Any]: '''simple docstring''' return len(self.dataset ) def __getitem__( self : Tuple , A__ : List[str] ) -> Optional[int]: '''simple docstring''' a__ : Any = self.dataset[i] a__ : Optional[Any] = self.process(A__ , **self.params ) return processed class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Tuple , A__ : Union[str, Any] , A__ : Any , A__ : str , A__ : Tuple=None ) -> Union[str, Any]: '''simple docstring''' a__ : Any = loader a__ : str = infer a__ : Dict = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether a__ : Optional[Any] = None a__ : List[Any] = loader_batch_size # Internal bookkeeping a__ : Tuple = None a__ : Optional[int] = None def __len__( self : List[Any] ) -> Any: '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ) -> Tuple: '''simple docstring''' a__ : Tuple = iter(self.loader ) return self def __lowerCAmelCase ( self : List[str] ) -> Tuple: '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice a__ : Tuple = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) a__ : Tuple = {} for k, element in self._loader_batch_data.items(): if isinstance(A__ , A__ ): # Convert ModelOutput to tuple first a__ : Optional[int] = element.to_tuple() if isinstance(element[0] , torch.Tensor ): a__ : Optional[int] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): a__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(A__ , A__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): a__ : Optional[int] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): a__ : Optional[int] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around a__ : Optional[int] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers a__ : Dict = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers a__ : Dict = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. a__ : List[str] = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 a__ : Dict = self._loader_batch_data.__class__(A__ ) self._loader_batch_index += 1 return result def __lowerCAmelCase ( self : List[Any] ) -> int: '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch a__ : int = next(self.iterator ) a__ : int = self.infer(A__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(A__ , torch.Tensor ): a__ : Any = processed else: a__ : List[str] = list(processed.keys() )[0] a__ : Dict = processed[key] if isinstance(A__ , A__ ): a__ : Tuple = len(A__ ) else: a__ : Optional[Any] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. a__ : List[str] = observed_batch_size # Setting internal index to unwrap the batch a__ : List[str] = processed a__ : Tuple = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[Any] , A__ : Optional[int] , A__ : Tuple , A__ : Optional[int] , A__ : Optional[Any]=None ) -> Optional[Any]: '''simple docstring''' super().__init__(A__ , A__ , A__ ) def __iter__( self : Optional[Any] ) -> str: '''simple docstring''' a__ : Union[str, Any] = iter(self.loader ) a__ : Dict = None return self def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' if self.subiterator is None: a__ : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item a__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators a__ : Tuple = self.infer(next(self.iterator ) , **self.params ) a__ : Optional[Any] = next(self.subiterator ) return processed class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __iter__( self : str ) -> Optional[int]: '''simple docstring''' a__ : Dict = iter(self.loader ) return self def __lowerCAmelCase ( self : str ) -> Tuple: '''simple docstring''' a__ : Dict = False a__ : List[str] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: a__ : List[str] = self.loader_batch_item() a__ : List[str] = item.pop('''is_last''' ) accumulator.append(A__ ) if is_last: return accumulator while not is_last: a__ : Optional[int] = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(A__ , torch.Tensor ): a__ : int = processed else: a__ : int = list(processed.keys() )[0] a__ : List[str] = processed[key] if isinstance(A__ , A__ ): a__ : List[Any] = len(A__ ) else: a__ : Union[str, Any] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. a__ : str = observed_batch_size a__ : int = processed a__ : Union[str, Any] = 0 while self._loader_batch_index < self.loader_batch_size: a__ : Dict = self.loader_batch_item() a__ : Any = item.pop('''is_last''' ) accumulator.append(A__ ) if is_last: return accumulator else: a__ : Tuple = processed a__ : List[str] = item.pop('''is_last''' ) accumulator.append(A__ ) return accumulator class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : int , A__ : Dataset , A__ : str ) -> int: '''simple docstring''' a__ : Any = dataset a__ : List[Any] = key def __len__( self : str ) -> int: '''simple docstring''' return len(self.dataset ) def __getitem__( self : int , A__ : List[str] ) -> str: '''simple docstring''' return self.dataset[i][self.key] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[Any] , A__ : Dataset , A__ : str , A__ : str ) -> List[str]: '''simple docstring''' a__ : Any = dataset a__ : Optional[Any] = keya a__ : Any = keya def __len__( self : Optional[int] ) -> List[Any]: '''simple docstring''' return len(self.dataset ) def __getitem__( self : Tuple , A__ : Union[str, Any] ) -> str: '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' def _lowerCamelCase ( lowerCamelCase_ : str = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" UpperCAmelCase_ : Any = set() # Replace all the whitespace in our sentence UpperCAmelCase_ : int = input_str.replace(' ' , '' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCamelCase_ ) == 26 def _lowerCamelCase ( lowerCamelCase_ : str = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" UpperCAmelCase_ : str = [False] * 26 for char in input_str: if char.islower(): UpperCAmelCase_ : Optional[Any] = True elif char.isupper(): UpperCAmelCase_ : str = True return all(lowerCamelCase_ ) def _lowerCamelCase ( lowerCamelCase_ : str = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _lowerCamelCase ( ): """simple docstring""" from timeit import timeit UpperCAmelCase_ : Dict = 'from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest' print(timeit('is_pangram()' , setup=lowerCamelCase_ ) ) print(timeit('is_pangram_faster()' , setup=lowerCamelCase_ ) ) print(timeit('is_pangram_fastest()' , setup=lowerCamelCase_ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
389
'''simple docstring''' def _lowerCamelCase ( lowerCamelCase_ : str , lowerCamelCase_ : int ): """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(lowerCamelCase_ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
389
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ = { """configuration_nllb_moe""": [ """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NllbMoeConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""", """NllbMoeForConditionalGeneration""", """NllbMoeModel""", """NllbMoePreTrainedModel""", """NllbMoeTop2Router""", """NllbMoeSparseMLP""", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
232
"""simple docstring""" # 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 from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A : Optional[int] = { """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""], """processing_mgp_str""": ["""MgpstrProcessor"""], """tokenization_mgp_str""": ["""MgpstrTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Any = [ """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""", """MgpstrModel""", """MgpstrPreTrainedModel""", """MgpstrForSceneTextRecognition""", ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys _A : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
361
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , _lowercase , _lowercase , _lowercase , **_lowercase ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = feature_size snake_case_ : Optional[int] = sampling_rate snake_case_ : Dict = padding_value snake_case_ : Any = kwargs.pop("""padding_side""" , """right""" ) snake_case_ : Dict = kwargs.pop("""return_attention_mask""" , _lowercase ) super().__init__(**_lowercase ) def UpperCAmelCase__ ( self , _lowercase , _lowercase = True , _lowercase = None , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(_lowercase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): snake_case_ : Optional[Any] = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( """You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`""" f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) snake_case_ : Union[str, Any] = processed_features[self.model_input_names[0]] snake_case_ : Tuple = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(_lowercase ) == 0: if return_attention_mask: snake_case_ : Dict = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch snake_case_ : Union[str, Any] = required_input[0] if isinstance(_lowercase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. snake_case_ : Any = 0 while len(required_input[index] ) == 0: index += 1 if index < len(_lowercase ): snake_case_ : Any = required_input[index][0] if return_tensors is None: if is_tf_tensor(_lowercase ): snake_case_ : Optional[Any] = """tf""" elif is_torch_tensor(_lowercase ): snake_case_ : Union[str, Any] = """pt""" elif isinstance(_lowercase , (int, float, list, tuple, np.ndarray) ): snake_case_ : int = """np""" else: raise ValueError( f'type of {first_element} unknown: {type(_lowercase )}. ' """Should be one of a python, numpy, pytorch or tensorflow object.""" ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): snake_case_ : Dict = to_numpy(_lowercase ) else: snake_case_ : Optional[int] = [to_numpy(_lowercase ) for v in value] # Convert padding_strategy in PaddingStrategy snake_case_ : List[str] = self._get_padding_strategies(padding=_lowercase , max_length=_lowercase ) snake_case_ : List[Any] = processed_features[self.model_input_names[0]] snake_case_ : str = len(_lowercase ) if not all(len(_lowercase ) == batch_size for v in processed_features.values() ): raise ValueError("""Some items in the output dictionary have a different batch size than others.""" ) snake_case_ : Any = [] for i in range(_lowercase ): snake_case_ : List[str] = {k: v[i] for k, v in processed_features.items()} # truncation snake_case_ : Any = self._truncate( _lowercase , max_length=_lowercase , pad_to_multiple_of=_lowercase , truncation=_lowercase , ) truncated_inputs.append(_lowercase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length snake_case_ : Optional[int] = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) snake_case_ : List[str] = PaddingStrategy.MAX_LENGTH snake_case_ : List[Any] = {} for i in range(_lowercase ): # padding snake_case_ : str = self._pad( truncated_inputs[i] , max_length=_lowercase , padding_strategy=_lowercase , pad_to_multiple_of=_lowercase , return_attention_mask=_lowercase , ) for key, value in outputs.items(): if key not in batch_outputs: snake_case_ : Optional[Any] = [] if value.dtype is np.dtype(np.floataa ): snake_case_ : List[Any] = value.astype(np.floataa ) batch_outputs[key].append(_lowercase ) return BatchFeature(_lowercase , tensor_type=_lowercase ) def UpperCAmelCase__ ( self , _lowercase , _lowercase = None , _lowercase = PaddingStrategy.DO_NOT_PAD , _lowercase = None , _lowercase = None , ) -> dict: '''simple docstring''' snake_case_ : List[Any] = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: snake_case_ : Dict = len(_lowercase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): snake_case_ : str = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of snake_case_ : str = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_lowercase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: snake_case_ : Any = np.ones(len(_lowercase ) , dtype=np.intaa ) if needs_to_be_padded: snake_case_ : Any = max_length - len(_lowercase ) if self.padding_side == "right": if return_attention_mask: snake_case_ : Any = np.pad( processed_features["""attention_mask"""] , (0, difference) ) snake_case_ : List[Any] = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) snake_case_ : Dict = np.pad( _lowercase , _lowercase , """constant""" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: snake_case_ : Optional[Any] = np.pad( processed_features["""attention_mask"""] , (difference, 0) ) snake_case_ : Optional[Any] = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) snake_case_ : Optional[Any] = np.pad( _lowercase , _lowercase , """constant""" , constant_values=self.padding_value ) else: raise ValueError("""Invalid padding strategy:""" + str(self.padding_side ) ) return processed_features def UpperCAmelCase__ ( self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = None , ) -> str: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("""When setting ``truncation=True``, make sure that ``max_length`` is defined.""" ) snake_case_ : Union[str, Any] = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): snake_case_ : Union[str, Any] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of snake_case_ : List[str] = len(_lowercase ) > max_length if needs_to_be_truncated: snake_case_ : Tuple = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: snake_case_ : Any = processed_features["""attention_mask"""][:max_length] return processed_features def UpperCAmelCase__ ( self , _lowercase=False , _lowercase=None ) -> Tuple: '''simple docstring''' if padding is not False: if padding is True: snake_case_ : Any = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(_lowercase , _lowercase ): snake_case_ : Union[str, Any] = PaddingStrategy(_lowercase ) elif isinstance(_lowercase , _lowercase ): snake_case_ : Dict = padding else: snake_case_ : List[Any] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( """Asking to pad but the feature_extractor does not have a padding value. Please select a value to use""" """ as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.""" ) return padding_strategy
715
"""simple docstring""" from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def __lowerCAmelCase ( __UpperCamelCase : int ): '''simple docstring''' def is_in_circle(__UpperCamelCase : float , __UpperCamelCase : float ) -> bool: snake_case_ : Dict = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle snake_case_ : Tuple = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(__UpperCamelCase ) ) # The ratio of the area for circle to square is pi/4. snake_case_ : Union[str, Any] = proportion * 4 print(F'The estimated value of pi is {pi_estimate}' ) print(F'The numpy value of pi is {pi}' ) print(F'The total error is {abs(pi - pi_estimate )}' ) def __lowerCAmelCase ( __UpperCamelCase : int , __UpperCamelCase : Callable[[float], float] , __UpperCamelCase : float = 0.0 , __UpperCamelCase : float = 1.0 , ): '''simple docstring''' return mean( function_to_integrate(uniform(__UpperCamelCase , __UpperCamelCase ) ) for _ in range(__UpperCamelCase ) ) * (max_value - min_value) def __lowerCAmelCase ( __UpperCamelCase : int , __UpperCamelCase : float = 0.0 , __UpperCamelCase : float = 1.0 ): '''simple docstring''' def identity_function(__UpperCamelCase : float ) -> float: return x snake_case_ : int = area_under_curve_estimator( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) snake_case_ : str = (max_value * max_value - min_value * min_value) / 2 print("""******************""" ) print(F'Estimating area under y=x where x varies from {min_value} to {max_value}' ) print(F'Estimated value is {estimated_value}' ) print(F'Expected value is {expected_value}' ) print(F'Total error is {abs(estimated_value - expected_value )}' ) print("""******************""" ) def __lowerCAmelCase ( __UpperCamelCase : int ): '''simple docstring''' def function_to_integrate(__UpperCamelCase : float ) -> float: return sqrt(4.0 - x * x ) snake_case_ : List[Any] = area_under_curve_estimator( __UpperCamelCase , __UpperCamelCase , 0.0 , 2.0 ) print("""******************""" ) print("""Estimating pi using area_under_curve_estimator""" ) print(F'Estimated value is {estimated_value}' ) print(F'Expected value is {pi}' ) print(F'Total error is {abs(estimated_value - pi )}' ) print("""******************""" ) if __name__ == "__main__": import doctest doctest.testmod()
21
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowerCamelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase__ = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __A(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=8 ) -> Any: """simple docstring""" _UpperCamelCase = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _UpperCamelCase = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( __lowercase ): def __init__( self , a , a , a , ) -> List[str]: '''simple docstring''' super().__init__() self.register_modules( unet=A_ , scheduler=A_ , movq=A_ , ) _UpperCamelCase = 2 ** (len(self.movq.config.block_out_channels ) - 1) def A_ ( self , a , a , a , a , a , a ) -> Union[str, Any]: '''simple docstring''' if latents is None: _UpperCamelCase = randn_tensor(A_ , generator=A_ , device=A_ , dtype=A_ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _UpperCamelCase = latents.to(A_ ) _UpperCamelCase = latents * scheduler.init_noise_sigma return latents def A_ ( self , a=0 ) -> Tuple: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _UpperCamelCase = torch.device(F'cuda:{gpu_id}' ) _UpperCamelCase = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A_ , A_ ) def A_ ( self , a=0 ) -> str: '''simple docstring''' if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _UpperCamelCase = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=A_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _UpperCamelCase = None for cpu_offloaded_model in [self.unet, self.movq]: _UpperCamelCase , _UpperCamelCase = cpu_offload_with_hook(A_ , A_ , prev_module_hook=A_ ) # We'll offload the last model manually. _UpperCamelCase = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def A_ ( self ) -> Optional[int]: '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(A_ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A_ ) def __call__( self , a , a , a , a = 5_12 , a = 5_12 , a = 1_00 , a = 4.0 , a = 1 , a = None , a = None , a = "pil" , a = True , ) -> List[Any]: '''simple docstring''' _UpperCamelCase = self._execution_device _UpperCamelCase = guidance_scale > 1.0 if isinstance(A_ , A_ ): _UpperCamelCase = torch.cat(A_ , dim=0 ) if isinstance(A_ , A_ ): _UpperCamelCase = torch.cat(A_ , dim=0 ) if isinstance(A_ , A_ ): _UpperCamelCase = torch.cat(A_ , dim=0 ) _UpperCamelCase = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: _UpperCamelCase = image_embeds.repeat_interleave(A_ , dim=0 ) _UpperCamelCase = negative_image_embeds.repeat_interleave(A_ , dim=0 ) _UpperCamelCase = hint.repeat_interleave(A_ , dim=0 ) _UpperCamelCase = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A_ ) _UpperCamelCase = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A_ ) self.scheduler.set_timesteps(A_ , device=A_ ) _UpperCamelCase = self.scheduler.timesteps _UpperCamelCase = self.movq.config.latent_channels _UpperCamelCase , _UpperCamelCase = downscale_height_and_width(A_ , A_ , self.movq_scale_factor ) # create initial latent _UpperCamelCase = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A_ , A_ , A_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A_ ) ): # expand the latents if we are doing classifier free guidance _UpperCamelCase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _UpperCamelCase = {"""image_embeds""": image_embeds, """hint""": hint} _UpperCamelCase = self.unet( sample=A_ , timestep=A_ , encoder_hidden_states=A_ , added_cond_kwargs=A_ , return_dict=A_ , )[0] if do_classifier_free_guidance: _UpperCamelCase , _UpperCamelCase = noise_pred.split(latents.shape[1] , dim=1 ) _UpperCamelCase , _UpperCamelCase = noise_pred.chunk(2 ) _UpperCamelCase , _UpperCamelCase = variance_pred.chunk(2 ) _UpperCamelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _UpperCamelCase = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _UpperCamelCase , _UpperCamelCase = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _UpperCamelCase = self.scheduler.step( A_ , A_ , A_ , generator=A_ , )[0] # post-processing _UpperCamelCase = self.movq.decode(A_ , force_not_quantize=A_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _UpperCamelCase = image * 0.5 + 0.5 _UpperCamelCase = image.clamp(0 , 1 ) _UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _UpperCamelCase = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
612
"""simple docstring""" from collections.abc import Callable def a_ ( lowercase__ :Callable[[float], float], lowercase__ :float, lowercase__ :float ): __lowerCamelCase = a __lowerCamelCase = b if function(lowercase__ ) == 0: # one of the a or b is a root for the function return a elif function(lowercase__ ) == 0: return b elif ( function(lowercase__ ) * function(lowercase__ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: __lowerCamelCase = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(lowercase__ ) == 0: return mid elif function(lowercase__ ) * function(lowercase__ ) < 0: __lowerCamelCase = mid else: __lowerCamelCase = mid __lowerCamelCase = start + (end - start) / 2.0 return mid def a_ ( lowercase__ :float ): return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_0_0_0)) import doctest doctest.testmod()
281
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Optional[Any] = '''roberta''' def __init__( self : int , SCREAMING_SNAKE_CASE__ : Dict=5_0_2_6_5 , SCREAMING_SNAKE_CASE__ : Dict=7_6_8 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Any=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : int=1E-12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]="absolute" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> List[Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) a_ : List[str] = vocab_size a_ : str = hidden_size a_ : List[Any] = num_hidden_layers a_ : Optional[Any] = num_attention_heads a_ : str = hidden_act a_ : str = intermediate_size a_ : List[Any] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : Dict = max_position_embeddings a_ : Dict = type_vocab_size a_ : List[str] = initializer_range a_ : Union[str, Any] = layer_norm_eps a_ : Optional[Any] = position_embedding_type a_ : Tuple = use_cache a_ : int = classifier_dropout class SCREAMING_SNAKE_CASE__ ( lowercase__ ): @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a_ : Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
702
from sklearn.metrics import fa_score import datasets UpperCAmelCase_ : List[Any] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' UpperCAmelCase_ : Optional[Any] = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' UpperCAmelCase_ : Optional[Any] = '\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def SCREAMING_SNAKE_CASE ( self : int ) -> int: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]="binary" , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Any: a_ : List[Any] = fa_score( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , pos_label=SCREAMING_SNAKE_CASE__ , average=SCREAMING_SNAKE_CASE__ , sample_weight=SCREAMING_SNAKE_CASE__ ) return {"f1": float(SCREAMING_SNAKE_CASE__ ) if score.size == 1 else score}
443
0
import math def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = [] lowercase__ = 2 lowercase__ = int(math.sqrt(SCREAMING_SNAKE_CASE ) ) # Size of every segment lowercase__ = [True] * (end + 1) lowercase__ = [] while start <= end: if temp[start] is True: in_prime.append(SCREAMING_SNAKE_CASE ) for i in range(start * start , end + 1 , SCREAMING_SNAKE_CASE ): lowercase__ = False start += 1 prime += in_prime lowercase__ = end + 1 lowercase__ = min(2 * end , SCREAMING_SNAKE_CASE ) while low <= n: lowercase__ = [True] * (high - low + 1) for each in in_prime: lowercase__ = math.floor(low / each ) * each if t < low: t += each for j in range(SCREAMING_SNAKE_CASE , high + 1 , SCREAMING_SNAKE_CASE ): lowercase__ = False for j in range(len(SCREAMING_SNAKE_CASE ) ): if temp[j] is True: prime.append(j + low ) lowercase__ = high + 1 lowercase__ = min(high + end , SCREAMING_SNAKE_CASE ) return prime print(sieve(10**6))
43
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) lowerCamelCase_ = logging.getLogger(__name__) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__a , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__a , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__a , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__a , default="""data/dump""" , help="""The dump file prefix.""" ) UpperCamelCase__ = parser.parse_args() logger.info(f"Loading Tokenizer ({args.tokenizer_name})" ) if args.tokenizer_type == "bert": UpperCamelCase__ = BertTokenizer.from_pretrained(args.tokenizer_name ) UpperCamelCase__ = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` UpperCamelCase__ = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": UpperCamelCase__ = RobertaTokenizer.from_pretrained(args.tokenizer_name ) UpperCamelCase__ = tokenizer.special_tokens_map["""cls_token"""] # `<s>` UpperCamelCase__ = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": UpperCamelCase__ = GPTaTokenizer.from_pretrained(args.tokenizer_name ) UpperCamelCase__ = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` UpperCamelCase__ = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(f"Loading text from {args.file_path}" ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: UpperCamelCase__ = fp.readlines() logger.info("""Start encoding""" ) logger.info(f"{len(__a )} examples to process." ) UpperCamelCase__ = [] UpperCamelCase__ = 0 UpperCamelCase__ = 10_000 UpperCamelCase__ = time.time() for text in data: UpperCamelCase__ = f"{bos} {text.strip()} {sep}" UpperCamelCase__ = tokenizer.encode(__a , add_special_tokens=__a ) rslt.append(__a ) iter += 1 if iter % interval == 0: UpperCamelCase__ = time.time() logger.info(f"{iter} examples processed. - {(end-start):.2f}s/{interval}expl" ) UpperCamelCase__ = time.time() logger.info("""Finished binarization""" ) logger.info(f"{len(__a )} examples processed." ) UpperCamelCase__ = f"{args.dump_file}.{args.tokenizer_name}.pickle" UpperCamelCase__ = tokenizer.vocab_size if vocab_size < (1 << 16): UpperCamelCase__ = [np.uintaa(__a ) for d in rslt] else: UpperCamelCase__ = [np.intaa(__a ) for d in rslt] random.shuffle(rslt_ ) logger.info(f"Dump to {dp_file}" ) with open(__a , """wb""" ) as handle: pickle.dump(rslt_ , __a , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
513
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self , lowercase__ ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): __A =model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(__UpperCamelCase ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sgugger/tiny-distilbert-classification''' __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , only_pretrain_model=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , torchscript=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , fpaa=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =AutoConfig.from_pretrained(__UpperCamelCase ) # set architectures equal to `None` __A =None __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase , configs=[config] ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__UpperCamelCase , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =AutoConfig.from_pretrained(__UpperCamelCase ) __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase , configs=[config] ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tinier_bart''' __A =AutoConfig.from_pretrained(__UpperCamelCase ) __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase , configs=[config] ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' __A =AutoConfig.from_pretrained(__UpperCamelCase ) __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase , configs=[config] ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tinier_bart''' __A =AutoConfig.from_pretrained(__UpperCamelCase ) __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase , configs=[config] ) __A =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , save_to_csv=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__UpperCamelCase , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(__UpperCamelCase , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(__UpperCamelCase , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(__UpperCamelCase , '''train_time.csv''' ) , env_info_csv_file=os.path.join(__UpperCamelCase , '''env.csv''' ) , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(__UpperCamelCase , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase , '''env.csv''' ) ).exists() ) def __UpperCamelCase ( self ): '''simple docstring''' __A ='''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(lowercase__ ): self.assertTrue(hasattr(__UpperCamelCase , '''sequential''' ) ) self.assertTrue(hasattr(__UpperCamelCase , '''cumulative''' ) ) self.assertTrue(hasattr(__UpperCamelCase , '''current''' ) ) self.assertTrue(hasattr(__UpperCamelCase , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__UpperCamelCase , inference=__UpperCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__UpperCamelCase , '''log.txt''' ) , log_print=__UpperCamelCase , trace_memory_line_by_line=__UpperCamelCase , multi_process=__UpperCamelCase , ) __A =PyTorchBenchmark(__UpperCamelCase ) __A =benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(__UpperCamelCase , '''log.txt''' ) ).exists() )
707
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _lowerCamelCase : List[str] = logging.get_logger(__name__) _lowerCamelCase : str = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } _lowerCamelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A__ ( __A : int , __A : Optional[int] , __A : List[Any] , __A : Any , __A : Optional[int] ) ->str: for attribute in key.split('''.''' ): __A =getattr(__A , __A ) if weight_type is not None: __A =getattr(__A , __A ).shape else: __A =hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": __A =value elif weight_type == "weight_g": __A =value elif weight_type == "weight_v": __A =value elif weight_type == "bias": __A =value elif weight_type == "running_mean": __A =value elif weight_type == "running_var": __A =value elif weight_type == "num_batches_tracked": __A =value elif weight_type == "inv_freq": __A =value else: __A =value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def A__ ( __A : Optional[int] , __A : Union[str, Any] , __A : str ) ->List[str]: __A =[] __A =fairseq_model.state_dict() __A =hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A =False if "conv_layers" in name: load_conv_layer( __A , __A , __A , __A , hf_model.config.feat_extract_norm == '''group''' , ) __A =True else: for key, mapped_key in MAPPING.items(): __A ='''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __A =True if "*" in mapped_key: __A =name.split(__A )[0].split('''.''' )[-2] __A =mapped_key.replace('''*''' , __A ) if "pos_bias_u" in name: __A =None elif "pos_bias_v" in name: __A =None elif "weight_g" in name: __A ='''weight_g''' elif "weight_v" in name: __A ='''weight_v''' elif "bias" in name: __A ='''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A ='''weight''' elif "running_mean" in name: __A ='''running_mean''' elif "inv_freq" in name: __A ='''inv_freq''' elif "running_var" in name: __A ='''running_var''' elif "num_batches_tracked" in name: __A ='''num_batches_tracked''' else: __A =None set_recursively(__A , __A , __A , __A , __A ) continue if not is_used: unused_weights.append(__A ) logger.warning(F'''Unused weights: {unused_weights}''' ) def A__ ( __A : Dict , __A : Optional[int] , __A : Optional[int] , __A : Union[str, Any] , __A : List[str] ) ->Any: __A =full_name.split('''conv_layers.''' )[-1] __A =name.split('''.''' ) __A =int(items[0] ) __A =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __A =value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __A =value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) __A =value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) __A =value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__A ) @torch.no_grad() def A__ ( __A : Optional[Any] , __A : Optional[Any] , __A : Any=None , __A : Optional[int]=None , __A : Dict=True ) ->Union[str, Any]: if config_path is not None: __A =WavaVecaConformerConfig.from_pretrained(__A , hidden_act='''swish''' ) else: __A =WavaVecaConformerConfig() if "rope" in checkpoint_path: __A ='''rotary''' if is_finetuned: if dict_path: __A =Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A =target_dict.pad_index __A =target_dict.bos_index __A =target_dict.eos_index __A =len(target_dict.symbols ) __A =os.path.join(__A , '''vocab.json''' ) if not os.path.isdir(__A ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__A ) ) return os.makedirs(__A , exist_ok=__A ) __A =target_dict.indices # fairseq has the <pad> and <s> switched __A =0 __A =1 with open(__A , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(__A , __A ) __A =WavaVecaCTCTokenizer( __A , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=__A , ) __A =True if config.feat_extract_norm == '''layer''' else False __A =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__A , return_attention_mask=__A , ) __A =WavaVecaProcessor(feature_extractor=__A , tokenizer=__A ) processor.save_pretrained(__A ) __A =WavaVecaConformerForCTC(__A ) else: __A =WavaVecaConformerForPreTraining(__A ) if is_finetuned: __A , __A , __A =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __A =argparse.Namespace(task='''audio_pretraining''' ) __A =fairseq.tasks.setup_task(__A ) __A , __A , __A =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=__A ) __A =model[0].eval() recursively_load_weights(__A , __A , not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": _lowerCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) _lowerCamelCase : Tuple = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
516
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
292
'''simple docstring''' def lowerCamelCase_ ( __UpperCamelCase : int ) -> bool: """simple docstring""" if num < 0: return False _A = num _A = 0 while num > 0: _A = rev_num * 1_0 + (num % 1_0) num //= 1_0 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
292
1
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
458
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _UpperCamelCase ( A,unittest.TestCase ): '''simple docstring''' a_ : Any = "ssube/stable-diffusion-x4-upscaler-onnx" def _snake_case ( self : Any , _lowerCamelCase : List[str]=0 ): '''simple docstring''' __lowerCamelCase : Union[str, Any] = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(_lowerCamelCase ) ) __lowerCamelCase : int = torch.manual_seed(_lowerCamelCase ) __lowerCamelCase : Union[str, Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _snake_case ( self : Optional[Any] ): '''simple docstring''' __lowerCamelCase : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : Tuple = self.get_dummy_inputs() __lowerCamelCase : Dict = pipe(**_lowerCamelCase ).images __lowerCamelCase : Dict = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : str = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def _snake_case ( self : Dict ): '''simple docstring''' __lowerCamelCase : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __lowerCamelCase : str = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : Tuple = self.get_dummy_inputs() __lowerCamelCase : Union[str, Any] = pipe(**_lowerCamelCase ).images __lowerCamelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : int = np.array( [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _snake_case ( self : Tuple ): '''simple docstring''' __lowerCamelCase : Optional[int] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __lowerCamelCase : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : List[str] = self.get_dummy_inputs() __lowerCamelCase : List[str] = pipe(**_lowerCamelCase ).images __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : str = np.array( [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _snake_case ( self : str ): '''simple docstring''' __lowerCamelCase : Optional[int] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __lowerCamelCase : Optional[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : Dict = self.get_dummy_inputs() __lowerCamelCase : Dict = pipe(**_lowerCamelCase ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : List[str] = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _snake_case ( self : Any ): '''simple docstring''' __lowerCamelCase : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" ) __lowerCamelCase : Union[str, Any] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : Optional[int] = self.get_dummy_inputs() __lowerCamelCase : int = pipe(**_lowerCamelCase ).images __lowerCamelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : Optional[int] = np.array( [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self : str ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _snake_case ( self : Tuple ): '''simple docstring''' __lowerCamelCase : Any = ort.SessionOptions() __lowerCamelCase : str = False return options def _snake_case ( self : Any ): '''simple docstring''' __lowerCamelCase : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __lowerCamelCase : Optional[Any] = init_image.resize((1_2_8, 1_2_8) ) # using the PNDM scheduler by default __lowerCamelCase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : List[Any] = """A fantasy landscape, trending on artstation""" __lowerCamelCase : str = torch.manual_seed(0 ) __lowerCamelCase : Any = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=1_0 , generator=_lowerCamelCase , output_type="""np""" , ) __lowerCamelCase : List[str] = output.images __lowerCamelCase : Any = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : int = np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _snake_case ( self : Any ): '''simple docstring''' __lowerCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) __lowerCamelCase : Union[str, Any] = init_image.resize((1_2_8, 1_2_8) ) __lowerCamelCase : str = LMSDiscreteScheduler.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , subfolder="""scheduler""" ) __lowerCamelCase : str = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" , scheduler=_lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : str = """A fantasy landscape, trending on artstation""" __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2_0 , generator=_lowerCamelCase , output_type="""np""" , ) __lowerCamelCase : int = output.images __lowerCamelCase : List[Any] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : List[str] = np.array( [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
458
1
import os import re import shutil import sys import tempfile import unittest import black __UpperCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. __UpperCAmelCase = ''' \""" Output class for the scheduler\'s step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \""" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None ''' class lowerCAmelCase_ ( unittest.TestCase ): def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : str = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir, 'schedulers/' ) ) UpperCamelCase : int = self.diffusers_dir shutil.copy( os.path.join(SCREAMING_SNAKE_CASE_, 'src/diffusers/schedulers/scheduling_ddpm.py' ), os.path.join(self.diffusers_dir, 'schedulers/scheduling_ddpm.py' ), ) def snake_case_ ( self ) -> List[str]: UpperCamelCase : Dict = 'src/diffusers' shutil.rmtree(self.diffusers_dir ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=None ) -> Optional[int]: UpperCamelCase : str = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: UpperCamelCase : List[Any] = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result UpperCamelCase : Union[str, Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119 ) UpperCamelCase : Any = black.format_str(SCREAMING_SNAKE_CASE_, mode=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = os.path.join(self.diffusers_dir, 'new_code.py' ) with open(SCREAMING_SNAKE_CASE_, 'w', newline='\n' ) as f: f.write(SCREAMING_SNAKE_CASE_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(SCREAMING_SNAKE_CASE_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name, overwrite=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_, 'r' ) as f: self.assertTrue(f.read(), SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> str: UpperCamelCase : Any = check_copies.find_code_in_diffusers('schedulers.scheduling_ddpm.DDPMSchedulerOutput' ) self.assertEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Union[str, Any]: # Base copy consistency self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput', 'DDPMSchedulerOutput', REFERENCE_CODE + '\n', ) # With no empty line at the end self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput', 'DDPMSchedulerOutput', SCREAMING_SNAKE_CASE_, ) # Copy consistency with rename self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test', 'TestSchedulerOutput', re.sub('DDPM', 'Test', SCREAMING_SNAKE_CASE_ ), ) # Copy consistency with a really long name UpperCamelCase : Any = 'TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason' self.check_copy_consistency( F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""", F"""{long_class_name}SchedulerOutput""", re.sub('Bert', SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), ) # Copy consistency with overwrite self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test', 'TestSchedulerOutput', SCREAMING_SNAKE_CASE_, overwrite_result=re.sub('DDPM', 'Test', SCREAMING_SNAKE_CASE_ ), )
40
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split lowercase_ = datasets.load_iris() lowercase_ = np.array(data['''data''']) lowercase_ = np.array(data['''target''']) lowercase_ = data['''target_names'''] lowercase_ , lowercase_ , lowercase_ , lowercase_ = train_test_split(X, y) def __lowerCAmelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] ) -> Optional[int]: return np.linalg.norm(np.array(__lowerCamelCase ) - np.array(__lowerCamelCase ) ) def __lowerCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int=5 ) -> str: __lowerCAmelCase =zip(__lowerCamelCase , __lowerCamelCase ) # List of distances of all points from the point to be classified __lowerCAmelCase =[] for data_point in data: __lowerCAmelCase =euclidean_distance(data_point[0] , __lowerCamelCase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. __lowerCAmelCase =[i[1] for i in sorted(__lowerCamelCase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified __lowerCAmelCase =Counter(__lowerCamelCase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
354
0
"""simple docstring""" from __future__ import annotations from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : int ) -> None: __SCREAMING_SNAKE_CASE = num_of_nodes __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = {} def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> None: self.m_edges.append([u_node, v_node, weight] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : int ) -> int: if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : int ) -> None: if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE = self.find_component(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : list[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> None: if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE = v_node component_size[v_node] += component_size[u_node] self.set_component(UpperCAmelCase__ ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE = self.find_component(UpperCAmelCase__ ) component_size[u_node] += component_size[v_node] self.set_component(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> None: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = edge __SCREAMING_SNAKE_CASE = self.m_component[u] __SCREAMING_SNAKE_CASE = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE = [u, v, w] for edge in minimum_weight_edge: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = edge __SCREAMING_SNAKE_CASE = self.m_component[u] __SCREAMING_SNAKE_CASE = self.m_component[v] if u_component != v_component: mst_weight += w self.union(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) print(F"""Added edge [{u} - {v}]\nAdded weight: {w}\n""" ) num_of_components -= 1 __SCREAMING_SNAKE_CASE = [-1] * self.m_num_of_nodes print(F"""The total weight of the minimal spanning tree is: {mst_weight}""" ) def UpperCAmelCase__ (): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
709
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if len(lowerCAmelCase_ ) < 2: raise ValueError("Monogons and Digons are not polygons in the Euclidean space" ) if any(i <= 0 for i in nums ): raise ValueError("All values must be greater than 0" ) __SCREAMING_SNAKE_CASE = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
553
0
import os import sys import transformers SCREAMING_SNAKE_CASE__ : Optional[Any] = """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)
0
"""simple docstring""" from math import log from scipy.constants import Boltzmann, physical_constants lowerCAmelCase_ = 300 # TEMPERATURE (unit = K) def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> float: if donor_conc <= 0: raise ValueError("""Donor concentration should be positive""" ) elif acceptor_conc <= 0: raise ValueError("""Acceptor concentration should be positive""" ) elif intrinsic_conc <= 0: raise ValueError("""Intrinsic concentration should be positive""" ) elif donor_conc <= intrinsic_conc: raise ValueError( """Donor concentration should be greater than intrinsic concentration""" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( """Acceptor concentration should be greater than intrinsic concentration""" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
338
0
import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _SCREAMING_SNAKE_CASE ( snake_case_ , unittest.TestCase ): lowerCAmelCase__ = MgpstrTokenizer lowerCAmelCase__ = False lowerCAmelCase__ = {} lowerCAmelCase__ = False def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: super().setUp() # fmt: off lowerCamelCase_ = ["[GO]", "[s]", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] # fmt: on lowerCamelCase_ = dict(zip(lowercase , range(len(lowercase ) ) ) ) lowerCamelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowercase ) + "\n" ) def SCREAMING_SNAKE_CASE_( self , **lowercase ) -> Tuple: return MgpstrTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Union[str, Any]: lowerCamelCase_ = "tester" lowerCamelCase_ = "tester" return input_text, output_text @unittest.skip("MGP-STR always lower cases letters." ) def SCREAMING_SNAKE_CASE_( self ) -> Tuple: pass def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: lowerCamelCase_ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): lowerCamelCase_ = "[SPECIAL_TOKEN]" tokenizer.add_special_tokens({"cls_token": special_token} ) lowerCamelCase_ = tokenizer.encode([special_token] , add_special_tokens=lowercase ) self.assertEqual(len(lowercase ) , 1 ) lowerCamelCase_ = tokenizer.decode(lowercase , skip_special_tokens=lowercase ) self.assertTrue(special_token not in decoded ) def SCREAMING_SNAKE_CASE_( self ) -> List[str]: lowerCamelCase_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): lowerCamelCase_ , lowerCamelCase_ = self.get_input_output_texts(lowercase ) lowerCamelCase_ = tokenizer.tokenize(lowercase ) lowerCamelCase_ = tokenizer.convert_tokens_to_ids(lowercase ) lowerCamelCase_ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) lowerCamelCase_ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertNotEqual(len(lowercase ) , 0 ) lowerCamelCase_ = tokenizer.decode(lowercase ) self.assertIsInstance(lowercase , lowercase ) self.assertEqual(text_a.replace(" " , "" ) , lowercase ) @unittest.skip("MGP-STR tokenizer only handles one sequence." ) def SCREAMING_SNAKE_CASE_( self ) -> str: pass @unittest.skip("inputs cannot be pretokenized in MgpstrTokenizer" ) def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: pass
711
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig __A =logging.get_logger(__name__) # General docstring __A ='''RegNetConfig''' # Base docstring __A ='''facebook/regnet-y-040''' __A =[1, 1_0_8_8, 7, 7] # Image classification docstring __A ='''facebook/regnet-y-040''' __A ='''tabby, tabby cat''' __A =[ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase = 3 , lowercase = 1 , lowercase = 1 , lowercase = "relu" , ) -> Dict: super().__init__() lowerCamelCase_ = nn.Convad( lowercase , lowercase , kernel_size=lowercase , stride=lowercase , padding=kernel_size // 2 , groups=lowercase , bias=lowercase , ) lowerCamelCase_ = nn.BatchNormad(lowercase ) lowerCamelCase_ = ACTaFN[activation] if activation is not None else nn.Identity() def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Optional[Any]: lowerCamelCase_ = self.convolution(lowercase ) lowerCamelCase_ = self.normalization(lowercase ) lowerCamelCase_ = self.activation(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase ) -> List[Any]: super().__init__() lowerCamelCase_ = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) lowerCamelCase_ = config.num_channels def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Union[str, Any]: lowerCamelCase_ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) lowerCamelCase_ = self.embedder(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase = 2 ) -> List[str]: super().__init__() lowerCamelCase_ = nn.Convad(lowercase , lowercase , kernel_size=1 , stride=lowercase , bias=lowercase ) lowerCamelCase_ = nn.BatchNormad(lowercase ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Tensor: lowerCamelCase_ = self.convolution(lowercase ) lowerCamelCase_ = self.normalization(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase ) -> List[Any]: super().__init__() lowerCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) lowerCamelCase_ = nn.Sequential( nn.Convad(lowercase , lowercase , kernel_size=1 ) , nn.ReLU() , nn.Convad(lowercase , lowercase , kernel_size=1 ) , nn.Sigmoid() , ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Union[str, Any]: # b c h w -> b c 1 1 lowerCamelCase_ = self.pooler(lowercase ) lowerCamelCase_ = self.attention(lowercase ) lowerCamelCase_ = hidden_state * attention return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase = 1 ) -> int: super().__init__() lowerCamelCase_ = in_channels != out_channels or stride != 1 lowerCamelCase_ = max(1 , out_channels // config.groups_width ) lowerCamelCase_ = ( RegNetShortCut(lowercase , lowercase , stride=lowercase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase_ = nn.Sequential( RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(lowercase , lowercase , stride=lowercase , groups=lowercase , activation=config.hidden_act ) , RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=lowercase ) , ) lowerCamelCase_ = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Dict: lowerCamelCase_ = hidden_state lowerCamelCase_ = self.layer(lowercase ) lowerCamelCase_ = self.shortcut(lowercase ) hidden_state += residual lowerCamelCase_ = self.activation(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase = 1 ) -> Dict: super().__init__() lowerCamelCase_ = in_channels != out_channels or stride != 1 lowerCamelCase_ = max(1 , out_channels // config.groups_width ) lowerCamelCase_ = ( RegNetShortCut(lowercase , lowercase , stride=lowercase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase_ = nn.Sequential( RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(lowercase , lowercase , stride=lowercase , groups=lowercase , activation=config.hidden_act ) , RegNetSELayer(lowercase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(lowercase , lowercase , kernel_size=1 , activation=lowercase ) , ) lowerCamelCase_ = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_( self , lowercase ) -> List[str]: lowerCamelCase_ = hidden_state lowerCamelCase_ = self.layer(lowercase ) lowerCamelCase_ = self.shortcut(lowercase ) hidden_state += residual lowerCamelCase_ = self.activation(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase , lowercase , lowercase , lowercase = 2 , lowercase = 2 , ) -> Optional[int]: super().__init__() lowerCamelCase_ = RegNetXLayer if config.layer_type == "x" else RegNetYLayer lowerCamelCase_ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( lowercase , lowercase , lowercase , stride=lowercase , ) , *[layer(lowercase , lowercase , lowercase ) for _ in range(depth - 1 )] , ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> int: lowerCamelCase_ = self.layers(lowercase ) return hidden_state class _SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self , lowercase ) -> int: super().__init__() lowerCamelCase_ = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowerCamelCase_ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(lowercase , config.depths[1:] ): self.stages.append(RegNetStage(lowercase , lowercase , lowercase , depth=lowercase ) ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = False , lowercase = True ) -> BaseModelOutputWithNoAttention: lowerCamelCase_ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCamelCase_ = hidden_states + (hidden_state,) lowerCamelCase_ = stage_module(lowercase ) if output_hidden_states: lowerCamelCase_ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=lowercase , hidden_states=lowercase ) class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = RegNetConfig lowerCAmelCase__ = 'regnet' lowerCAmelCase__ = 'pixel_values' lowerCAmelCase__ = True def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Any: if isinstance(lowercase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="fan_out" , nonlinearity="relu" ) elif isinstance(lowercase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=False ) -> Any: if isinstance(lowercase , lowercase ): lowerCamelCase_ = value __A =R''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' __A =R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , snake_case_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class _SCREAMING_SNAKE_CASE ( snake_case_ ): def __init__( self , lowercase ) -> List[str]: super().__init__(lowercase ) lowerCamelCase_ = config lowerCamelCase_ = RegNetEmbeddings(lowercase ) lowerCamelCase_ = RegNetEncoder(lowercase ) lowerCamelCase_ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=lowercase , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = None , lowercase = None ) -> BaseModelOutputWithPoolingAndNoAttention: lowerCamelCase_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.embedder(lowercase ) lowerCamelCase_ = self.encoder( lowercase , output_hidden_states=lowercase , return_dict=lowercase ) lowerCamelCase_ = encoder_outputs[0] lowerCamelCase_ = self.pooler(lowercase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=lowercase , pooler_output=lowercase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , snake_case_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class _SCREAMING_SNAKE_CASE ( snake_case_ ): def __init__( self , lowercase ) -> Any: super().__init__(lowercase ) lowerCamelCase_ = config.num_labels lowerCamelCase_ = RegNetModel(lowercase ) # classification head lowerCamelCase_ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def SCREAMING_SNAKE_CASE_( self , lowercase = None , lowercase = None , lowercase = None , lowercase = None , ) -> ImageClassifierOutputWithNoAttention: lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.regnet(lowercase , output_hidden_states=lowercase , return_dict=lowercase ) lowerCamelCase_ = outputs.pooler_output if return_dict else outputs[1] lowerCamelCase_ = self.classifier(lowercase ) lowerCamelCase_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCamelCase_ = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCamelCase_ = "single_label_classification" else: lowerCamelCase_ = "multi_label_classification" if self.config.problem_type == "regression": lowerCamelCase_ = MSELoss() if self.num_labels == 1: lowerCamelCase_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowerCamelCase_ = loss_fct(lowercase , lowercase ) elif self.config.problem_type == "single_label_classification": lowerCamelCase_ = CrossEntropyLoss() lowerCamelCase_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCamelCase_ = BCEWithLogitsLoss() lowerCamelCase_ = loss_fct(lowercase , lowercase ) if not return_dict: lowerCamelCase_ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowercase , logits=lowercase , hidden_states=outputs.hidden_states )
313
0
def __lowercase ( snake_case, snake_case ): """simple docstring""" _validate_point(snake_case ) _validate_point(snake_case ) if len(snake_case ) != len(snake_case ): raise ValueError('''Both points must be in the same n-dimensional space''' ) return float(sum(abs(a - b ) for a, b in zip(snake_case, snake_case ) ) ) def __lowercase ( snake_case ): """simple docstring""" if point: if isinstance(snake_case, snake_case ): for item in point: if not isinstance(snake_case, (int, float) ): __magic_name__ :str = ( '''Expected a list of numbers as input, found ''' f'''{type(snake_case ).__name__}''' ) raise TypeError(snake_case ) else: __magic_name__ :List[Any] = f'''Expected a list of numbers as input, found {type(snake_case ).__name__}''' raise TypeError(snake_case ) else: raise ValueError('''Missing an input''' ) def __lowercase ( snake_case, snake_case ): """simple docstring""" _validate_point(snake_case ) _validate_point(snake_case ) if len(snake_case ) != len(snake_case ): raise ValueError('''Both points must be in the same n-dimensional space''' ) return float(sum(abs(x - y ) for x, y in zip(snake_case, snake_case ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowerCamelCase_ ( lowerCamelCase ): def __init__( self , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[int] = params __magic_name__ :Any = np.array(__lowerCAmelCase ) __magic_name__ :Optional[Any] = np.array([len(__lowerCAmelCase ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , __lowerCAmelCase ): """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self ): """simple docstring""" return len(self.lengths ) def A ( self ): """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def A ( self ): """simple docstring""" __magic_name__ :Any = self.params.max_model_input_size __magic_name__ :int = self.lengths > max_len logger.info(F'''Splitting {sum(__lowerCAmelCase )} too long sequences.''' ) def divide_chunks(__lowerCAmelCase , __lowerCAmelCase ): return [l[i : i + n] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase )] __magic_name__ :Optional[int] = [] __magic_name__ :List[Any] = [] if self.params.mlm: __magic_name__ , __magic_name__ :Optional[Any] = self.params.special_tok_ids['''cls_token'''], self.params.special_tok_ids['''sep_token'''] else: __magic_name__ , __magic_name__ :Tuple = self.params.special_tok_ids['''bos_token'''], self.params.special_tok_ids['''eos_token'''] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: __magic_name__ :int = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: __magic_name__ :List[Any] = np.insert(__lowerCAmelCase , 0 , __lowerCAmelCase ) if sub_s[-1] != sep_id: __magic_name__ :Union[str, Any] = np.insert(__lowerCAmelCase , len(__lowerCAmelCase ) , __lowerCAmelCase ) assert len(__lowerCAmelCase ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(__lowerCAmelCase ) new_tok_ids.extend(__lowerCAmelCase ) new_lengths.extend([len(__lowerCAmelCase ) for l in sub_seqs] ) __magic_name__ :Tuple = np.array(__lowerCAmelCase ) __magic_name__ :Optional[int] = np.array(__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Optional[Any] = len(self ) __magic_name__ :int = self.lengths > 1_1 __magic_name__ :List[str] = self.token_ids[indices] __magic_name__ :Union[str, Any] = self.lengths[indices] __magic_name__ :List[str] = len(self ) logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def A ( self ): """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: __magic_name__ :Tuple = self.params.special_tok_ids['''unk_token'''] __magic_name__ :Dict = len(self ) __magic_name__ :Tuple = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) __magic_name__ :int = (unk_occs / self.lengths) < 0.5 __magic_name__ :str = self.token_ids[indices] __magic_name__ :str = self.lengths[indices] __magic_name__ :Any = len(self ) logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def A ( self ): """simple docstring""" if not self.params.is_master: return logger.info(F'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def A ( self , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = [t[0] for t in batch] __magic_name__ :List[Any] = [t[1] for t in batch] assert len(__lowerCAmelCase ) == len(__lowerCAmelCase ) # Max for paddings __magic_name__ :Tuple = max(__lowerCAmelCase ) # Pad token ids if self.params.mlm: __magic_name__ :Any = self.params.special_tok_ids['''pad_token'''] else: __magic_name__ :str = self.params.special_tok_ids['''unk_token'''] __magic_name__ :Any = [list(t.astype(__lowerCAmelCase ) ) + [pad_idx] * (max_seq_len_ - len(__lowerCAmelCase )) for t in token_ids] assert len(tk_ ) == len(__lowerCAmelCase ) assert all(len(__lowerCAmelCase ) == max_seq_len_ for t in tk_ ) __magic_name__ :Optional[int] = torch.tensor(tk_ ) # (bs, max_seq_len_) __magic_name__ :Optional[int] = torch.tensor(__lowerCAmelCase ) # (bs) return tk_t, lg_t
0
1
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=lowercase__): UpperCamelCase__ : Union[str, Any] =["""speech"""] def __init__( self : List[Any], *__lowercase : Optional[Any], **__lowercase : str ): requires_backends(self, ["speech"] ) class _snake_case ( metaclass=lowercase__): UpperCamelCase__ : Optional[Any] =["""speech"""] def __init__( self : Union[str, Any], *__lowercase : List[Any], **__lowercase : Tuple ): requires_backends(self, ["speech"] )
37
import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class _snake_case ( unittest.TestCase): def __init__( self : Dict, __lowercase : int, __lowercase : Union[str, Any]=7, __lowercase : Union[str, Any]=3, __lowercase : Any=18, __lowercase : Union[str, Any]=30, __lowercase : Any=400, __lowercase : List[str]=True, __lowercase : Dict=None, __lowercase : List[str]=True, __lowercase : int=False, __lowercase : Union[str, Any]=True, __lowercase : str=True, __lowercase : Optional[int]=[0.5, 0.5, 0.5], __lowercase : List[Any]=[0.5, 0.5, 0.5], ): lowercase__ = parent lowercase__ = batch_size lowercase__ = num_channels lowercase__ = image_size lowercase__ = min_resolution lowercase__ = max_resolution lowercase__ = do_resize lowercase__ = size if size is not None else {"height": 18, "width": 20} lowercase__ = do_thumbnail lowercase__ = do_align_axis lowercase__ = do_pad lowercase__ = do_normalize lowercase__ = image_mean lowercase__ = image_std def A__ ( self : Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class _snake_case ( lowercase__ , unittest.TestCase): UpperCamelCase__ : Optional[int] =DonutImageProcessor if is_vision_available() else None def A__ ( self : str ): lowercase__ = DonutImageProcessingTester(self ) @property def A__ ( self : List[str] ): return self.image_processor_tester.prepare_image_processor_dict() def A__ ( self : Optional[Any] ): lowercase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase, "do_resize" ) ) self.assertTrue(hasattr(__lowercase, "size" ) ) self.assertTrue(hasattr(__lowercase, "do_thumbnail" ) ) self.assertTrue(hasattr(__lowercase, "do_align_long_axis" ) ) self.assertTrue(hasattr(__lowercase, "do_pad" ) ) self.assertTrue(hasattr(__lowercase, "do_normalize" ) ) self.assertTrue(hasattr(__lowercase, "image_mean" ) ) self.assertTrue(hasattr(__lowercase, "image_std" ) ) def A__ ( self : str ): lowercase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {"height": 18, "width": 20} ) lowercase__ = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {"height": 42, "width": 42} ) # Previous config had dimensions in (width, height) order lowercase__ = self.image_processing_class.from_dict(self.image_processor_dict, size=(42, 84) ) self.assertEqual(image_processor.size, {"height": 84, "width": 42} ) def A__ ( self : List[str] ): pass @is_flaky() def A__ ( self : Dict ): # Initialize image_processing lowercase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__ = prepare_image_inputs(self.image_processor_tester, equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase, Image.Image ) # Test not batched input lowercase__ = image_processing(image_inputs[0], return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) # Test batched lowercase__ = image_processing(__lowercase, return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) @is_flaky() def A__ ( self : Optional[Any] ): # Initialize image_processing lowercase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase__ = prepare_image_inputs(self.image_processor_tester, equal_resolution=__lowercase, numpify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase, np.ndarray ) # Test not batched input lowercase__ = image_processing(image_inputs[0], return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) # Test batched lowercase__ = image_processing(__lowercase, return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) @is_flaky() def A__ ( self : Tuple ): # Initialize image_processing lowercase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase__ = prepare_image_inputs(self.image_processor_tester, equal_resolution=__lowercase, torchify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase, torch.Tensor ) # Test not batched input lowercase__ = image_processing(image_inputs[0], return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) # Test batched lowercase__ = image_processing(__lowercase, return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), )
37
1
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class A ( unittest.TestCase ): def __lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCAmelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" _a = 1 _a = 3 _a = (32, 32) _a = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) return image @property def __lowerCAmelCase ( self : Tuple ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) return model @property def __lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def __lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" torch.manual_seed(0 ) _a = 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=10_00 , ) return CLIPTextModel(lowerCAmelCase_ ) @property def __lowerCAmelCase ( self : Dict ) -> str: """simple docstring""" def extract(*lowerCAmelCase_ : str , **lowerCAmelCase_ : List[Any] ): class A : def __init__( self : Dict ) -> int: """simple docstring""" _a = torch.ones([0] ) def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : List[Any] ) -> Optional[Any]: """simple docstring""" self.pixel_values.to(lowerCAmelCase_ ) return self return Out() return extract def __lowerCAmelCase ( self : str ) -> Tuple: """simple docstring""" _a = '''cpu''' # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # make sure here that pndm scheduler skips prk _a = StableDiffusionPipeline( unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , feature_extractor=self.dummy_extractor , ) _a = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = '''A painting of a squirrel eating a burger''' _a = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 ) _a = sd_pipe([prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' ) _a = output.images _a = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , return_dict=lowerCAmelCase_ , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : List[Any] ) -> List[str]: """simple docstring""" _a = '''cpu''' # ensure determinism for the device-dependent torch.Generator _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=lowerCAmelCase_ ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # make sure here that pndm scheduler skips prk _a = StableDiffusionPipeline( unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , feature_extractor=self.dummy_extractor , ) _a = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = '''A painting of a squirrel eating a burger''' _a = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 ) _a = sd_pipe([prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' ) _a = output.images _a = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , return_dict=lowerCAmelCase_ , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" _a = StableDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-lms-pipe''' , safety_checker=lowerCAmelCase_ ) assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) assert isinstance(pipe.scheduler , lowerCAmelCase_ ) assert pipe.safety_checker is None _a = pipe('''example prompt''' , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase_ ) _a = StableDiffusionPipeline.from_pretrained(lowerCAmelCase_ ) # sanity check that the pipeline still works assert pipe.safety_checker is None _a = pipe('''example prompt''' , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def __lowerCAmelCase ( self : int ) -> List[Any]: """simple docstring""" _a = self.dummy_cond_unet _a = PNDMScheduler(skip_prk_steps=lowerCAmelCase_ ) _a = self.dummy_vae _a = self.dummy_text_encoder _a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # put models in fp16 _a = unet.half() _a = vae.half() _a = bert.half() # make sure here that pndm scheduler skips prk _a = StableDiffusionPipeline( unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , feature_extractor=self.dummy_extractor , ) _a = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = '''A painting of a squirrel eating a burger''' _a = sd_pipe([prompt] , num_inference_steps=2 , output_type='''np''' ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class A ( unittest.TestCase ): def __lowerCAmelCase ( self : List[Any] ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" _a = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' , safety_checker=lowerCAmelCase_ ) _a = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) _a = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = ( '''portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle''' ''' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with''' ''' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and''' ''' children from bahnhof zoo, detailed ''' ) _a = 40_03_66_03_46 _a = 7 # without safety guidance (sld_guidance_scale = 0) _a = torch.manual_seed(lowerCAmelCase_ ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) _a = output.images _a = image[0, -3:, -3:, -1] _a = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) _a = torch.manual_seed(lowerCAmelCase_ ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) _a = output.images _a = image[0, -3:, -3:, -1] _a = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : int ) -> Union[str, Any]: """simple docstring""" _a = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' , safety_checker=lowerCAmelCase_ ) _a = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) _a = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = '''padme amidala taking a bath artwork, safe for work, no nudity''' _a = 27_34_97_17_55 _a = 7 _a = torch.manual_seed(lowerCAmelCase_ ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) _a = output.images _a = image[0, -3:, -3:, -1] _a = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 _a = torch.manual_seed(lowerCAmelCase_ ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) _a = output.images _a = image[0, -3:, -3:, -1] _a = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" _a = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' ) _a = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _a = ( '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.''' ''' leyendecker''' ) _a = 10_44_35_52_34 _a = 12 _a = torch.manual_seed(lowerCAmelCase_ ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) _a = output.images _a = image[0, -3:, -3:, -1] _a = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 _a = torch.manual_seed(lowerCAmelCase_ ) _a = sd_pipe( [prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) _a = output.images _a = image[0, -3:, -3:, -1] _a = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
22
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class __lowercase ( unittest.TestCase ): @parameterized.expand([(None,), ('foo.json',)]) def _a ( self , lowercase_) -> int: __snake_case = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) __snake_case = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 5_0) self.assertEqual(loaded_config.max_length , 2_0) self.assertEqual(loaded_config.max_time , lowercase_) def _a ( self) -> Optional[int]: __snake_case = AutoConfig.from_pretrained('gpt2') __snake_case = GenerationConfig.from_model_config(lowercase_) __snake_case = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _a ( self) -> str: __snake_case = GenerationConfig() __snake_case = { 'max_new_tokens': 1_0_2_4, 'foo': 'bar', } __snake_case = copy.deepcopy(lowercase_) __snake_case = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1_0_2_4) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'foo': 'bar'}) def _a ( self) -> Optional[Any]: __snake_case = GenerationConfig() __snake_case = 'bar' with tempfile.TemporaryDirectory('test-generation-config') as tmp_dir: generation_config.save_pretrained(lowercase_) __snake_case = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , 'bar') __snake_case = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , 'foo') # no new kwargs should be initialized if from config def _a ( self) -> Optional[Any]: __snake_case = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) __snake_case = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) __snake_case = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class __lowercase ( unittest.TestCase ): @classmethod def _a ( cls) -> List[str]: __snake_case = TOKEN HfFolder.save_token(lowercase_) @classmethod def _a ( cls) -> Dict: try: delete_repo(token=cls._token , repo_id='test-generation-config') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org') except HTTPError: pass def _a ( self) -> List[Any]: __snake_case = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('test-generation-config' , use_auth_token=self._token) __snake_case = GenerationConfig.from_pretrained(F"{USER}/test-generation-config") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='test-generation-config') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='test-generation-config' , push_to_hub=lowercase_ , use_auth_token=self._token) __snake_case = GenerationConfig.from_pretrained(F"{USER}/test-generation-config") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _a ( self) -> str: __snake_case = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token) __snake_case = GenerationConfig.from_pretrained('valid_org/test-generation-config-org') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='valid_org/test-generation-config-org' , push_to_hub=lowercase_ , use_auth_token=self._token) __snake_case = GenerationConfig.from_pretrained('valid_org/test-generation-config-org') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
313
0
"""simple docstring""" def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> str: if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) a : Optional[Any] = str(bin(UpperCAmelCase__ ) ) binary_number += "0" * shift_amount return binary_number def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> str: if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) a : List[str] = str(bin(UpperCAmelCase__ ) )[2:] if shift_amount >= len(UpperCAmelCase__ ): return "0b0" a : Optional[int] = binary_number[: len(UpperCAmelCase__ ) - shift_amount] return "0b" + shifted_binary_number def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> str: if number >= 0: # Get binary representation of positive number a : Dict = '0' + str(bin(UpperCAmelCase__ ) ).strip('-' )[2:] else: # Get binary (2's complement) representation of negative number a : Optional[Any] = len(bin(UpperCAmelCase__ )[3:] ) # Find 2's complement of number a : str = bin(abs(UpperCAmelCase__ ) - (1 << binary_number_length) )[3:] a : str = ( '1' + '0' * (binary_number_length - len(UpperCAmelCase__ )) + binary_number ) if shift_amount >= len(UpperCAmelCase__ ): return "0b" + binary_number[0] * len(UpperCAmelCase__ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(UpperCAmelCase__ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
509
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : int = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Tuple = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class A_ ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowercase : str = CamembertTokenizer lowercase : str = CamembertTokenizerFast lowercase : List[str] = True lowercase : Tuple = True def lowercase_ ( self ) -> Tuple: super().setUp() # We have a SentencePiece fixture for testing a : List[str] = CamembertTokenizer(__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase_ ( self ) -> int: a : Dict = '<pad>' a : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def lowercase_ ( self ) -> List[str]: a : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(__UpperCAmelCase ) , 10_04 ) def lowercase_ ( self ) -> Optional[int]: self.assertEqual(self.get_tokenizer().vocab_size , 10_05 ) def lowercase_ ( self ) -> int: a : List[str] = CamembertTokenizer(__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) a : str = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) a : Tuple = 'I was born in 92000, and this is falsé.' a : Union[str, Any] = tokenizer.encode(__UpperCAmelCase ) a : Union[str, Any] = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) a : Dict = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) a : Tuple = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) a : Tuple = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) a : Tuple = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def lowercase_ ( self ) -> str: if not self.test_rust_tokenizer: return a : Tuple = self.get_tokenizer() a : List[str] = self.get_rust_tokenizer() a : Optional[Any] = 'I was born in 92000, and this is falsé.' a : Optional[int] = tokenizer.tokenize(__UpperCAmelCase ) a : str = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) a : Optional[int] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) a : Tuple = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) a : str = self.get_rust_tokenizer() a : List[Any] = tokenizer.encode(__UpperCAmelCase ) a : List[Any] = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def lowercase_ ( self ) -> List[str]: # fmt: off a : Optional[int] = {'input_ids': [[5, 54, 71_96, 2_97, 30, 23, 7_76, 18, 11, 32_15, 37_05, 82_52, 22, 31_64, 11_81, 21_16, 29, 16, 8_13, 25, 7_91, 33_14, 20, 34_46, 38, 2_75_75, 1_20, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_68, 17, 11, 90_88, 20, 15_17, 8, 2_28_04, 1_88_18, 10, 38, 6_29, 6_07, 6_07, 1_42, 19, 71_96, 8_67, 56, 1_03_26, 24, 22_67, 20, 4_16, 50_72, 1_56_12, 2_33, 7_34, 7, 23_99, 27, 16, 30_15, 16_49, 7, 24, 20, 43_38, 23_99, 27, 13, 34_00, 14, 13, 61_89, 8, 9_30, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. a : Any = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=__UpperCAmelCase , )
509
1