code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" lowerCAmelCase__ = { 0: '''0''', 1: '''1''', 2: '''2''', 3: '''3''', 4: '''4''', 5: '''5''', 6: '''6''', 7: '''7''', 8: '''8''', 9: '''9''', 10: '''a''', 11: '''b''', 12: '''c''', 13: '''d''', 14: '''e''', 15: '''f''', } def snake_case_ ( A_ : float ): '''simple docstring''' assert type(A_ ) in (int, float) and decimal == int(A_ ) _lowerCamelCase : Union[str, Any] = int(A_ ) _lowerCamelCase : Any = '''''' _lowerCamelCase : Optional[Any] = False if decimal < 0: _lowerCamelCase : Union[str, Any] = True decimal *= -1 while decimal > 0: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = divmod(A_, 16 ) _lowerCamelCase : List[Any] = values[remainder] + hexadecimal _lowerCamelCase : List[str] = '''0x''' + hexadecimal if negative: _lowerCamelCase : List[Any] = '''-''' + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( A_ : Dict, A_ : bool = True, A_ : float = math.inf, A_ : float = -math.inf, A_ : float = math.inf, A_ : float = -math.inf, A_ : bool = False, A_ : float = 1_00, A_ : float = 0.01, A_ : float = 1, ): '''simple docstring''' _lowerCamelCase : Optional[int] = False _lowerCamelCase : str = search_prob _lowerCamelCase : str = start_temperate _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : int = 0 _lowerCamelCase : Any = None while not search_end: _lowerCamelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCamelCase : Tuple = current_state scores.append(A_ ) iterations += 1 _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCamelCase : List[Any] = random.randint(0, len(A_ ) - 1 ) # picking a random neighbor _lowerCamelCase : Dict = neighbors.pop(A_ ) _lowerCamelCase : Union[str, Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCamelCase : Optional[Any] = picked_neighbor else: _lowerCamelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCamelCase : Union[str, Any] = picked_neighbor _lowerCamelCase : List[str] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCamelCase : Tuple = True else: _lowerCamelCase : Optional[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A_ ), A_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def snake_case_ ( A_ : Optional[int], A_ : List[Any] ): '''simple docstring''' return (3 * x**2) - (6 * y) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
83
1
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( A_ : Dict, A_ : bool = True, A_ : float = math.inf, A_ : float = -math.inf, A_ : float = math.inf, A_ : float = -math.inf, A_ : bool = False, A_ : float = 1_00, A_ : float = 0.01, A_ : float = 1, ): '''simple docstring''' _lowerCamelCase : Optional[int] = False _lowerCamelCase : str = search_prob _lowerCamelCase : str = start_temperate _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : int = 0 _lowerCamelCase : Any = None while not search_end: _lowerCamelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCamelCase : Tuple = current_state scores.append(A_ ) iterations += 1 _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCamelCase : List[Any] = random.randint(0, len(A_ ) - 1 ) # picking a random neighbor _lowerCamelCase : Dict = neighbors.pop(A_ ) _lowerCamelCase : Union[str, Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCamelCase : Optional[Any] = picked_neighbor else: _lowerCamelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCamelCase : Union[str, Any] = picked_neighbor _lowerCamelCase : List[str] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCamelCase : Tuple = True else: _lowerCamelCase : Optional[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A_ ), A_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def snake_case_ ( A_ : Optional[int], A_ : List[Any] ): '''simple docstring''' return (3 * x**2) - (6 * y) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
83
"""simple docstring""" from collections import namedtuple lowerCAmelCase__ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase__ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def snake_case_ ( A_ : float, A_ : str, A_ : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ''', '''.join(A_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ''', '''.join(A_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase__ = logging.getLogger(__name__) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[Any] = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''', type=A_, default='''wikitext''', help='''Name of the training. Explore datasets at: hf.co/datasets.''', ) parser.add_argument( '''--dataset_config''', type=A_, default='''wikitext-103-raw-v1''', help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''', type=A_, default='''sayakpaul/unigram-tokenizer-wikitext''', help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''', ) parser.add_argument( '''--shard_size''', type=A_, default=10_00, help='''Number of entries to go in a single shard.''', ) parser.add_argument('''--split''', type=A_, default='''train''', choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''', default=A_, type=A_, help='''Limit the number of shards (used for debugging).''', ) parser.add_argument( '''--max_length''', type=A_, default=5_12, help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''', ) parser.add_argument( '''--output_dir''', default='''tf-tpu''', type=A_, help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''', ) _lowerCamelCase : int = parser.parse_args() return args def snake_case_ ( A_ : Optional[Any] ): '''simple docstring''' def fn(A_ : str ): return tokenizer(examples['''text'''] ) return fn def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' _lowerCamelCase : Optional[int] = [] for i in range(len(tokenized_data['''input_ids'''] ) ): _lowerCamelCase : str = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } _lowerCamelCase : Union[str, Any] = tf.train.Features(feature=A_ ) _lowerCamelCase : int = tf.train.Example(features=A_ ) _lowerCamelCase : int = example.SerializeToString() records.append(A_ ) return records def snake_case_ ( A_ : Optional[Any] ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = datasets.load_dataset(args.dataset_name, args.dataset_config, split=args.split ) if args.limit is not None: _lowerCamelCase : Optional[int] = min(len(A_ ), args.limit ) _lowerCamelCase : Tuple = dataset.select(range(A_ ) ) print(F'''Limiting the dataset to {args.limit} entries.''' ) _lowerCamelCase : int = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) _lowerCamelCase : List[Any] = os.path.join(args.output_dir, args.split ) if not os.path.exists(A_ ): os.makedirs(A_ ) else: _lowerCamelCase : Any = os.path.join(args.output_dir, args.split ) # Tokenize the whole dataset at once. _lowerCamelCase : Tuple = tokenize_function(A_ ) _lowerCamelCase : Dict = dataset.map(A_, batched=A_, num_proc=4, remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(A_ : int ): # Concatenate all texts. _lowerCamelCase : Union[str, Any] = {k: sum(examples[k], [] ) for k in examples.keys()} _lowerCamelCase : Any = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 _lowerCamelCase : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. _lowerCamelCase : List[str] = { k: [t[i : i + args.max_length] for i in range(0, A_, args.max_length )] for k, t in concatenated_examples.items() } return result _lowerCamelCase : str = dataset_tokenized.map(A_, batched=A_, batch_size=10_00, num_proc=4 ) _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : Optional[int] = 0 for shard in range(0, len(A_ ), args.shard_size ): _lowerCamelCase : Tuple = grouped_dataset[shard : shard + args.shard_size] _lowerCamelCase : Union[str, Any] = len(dataset_snapshot['''input_ids'''] ) _lowerCamelCase : List[str] = os.path.join(A_, F'''dataset-{shard_count}-{records_containing}.tfrecord''' ) _lowerCamelCase : List[Any] = get_serialized_examples(A_ ) with tf.io.TFRecordWriter(A_ ) as out_file: for i in range(len(A_ ) ): _lowerCamelCase : str = serialized_examples[i] out_file.write(A_ ) print('''Wrote file {} containing {} records'''.format(A_, A_ ) ) shard_count += 1 total_records += records_containing with open(F'''split-{args.split}-records-count.txt''', '''w''' ) as f: print(F'''Total {args.split} records: {total_records}''', file=A_ ) if __name__ == "__main__": lowerCAmelCase__ = parse_args() main(args)
83
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case ( _lowercase): def __init__( self : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=9_9 , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : Optional[int]=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : int=5_1_2 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any="None" , __lowerCAmelCase : str=3 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[Any]=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Dict = use_input_mask _lowerCamelCase : Tuple = use_token_type_ids _lowerCamelCase : Optional[Any] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Optional[int] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : int = relative_attention _lowerCamelCase : Union[str, Any] = position_biased_input _lowerCamelCase : str = pos_att_type _lowerCamelCase : Tuple = scope def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : int = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : str = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : List[Any] = model(__lowerCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : Dict = DebertaVaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : Tuple = DebertaVaForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = DebertaVaForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : int = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True snake_case__ : List[Any] = False snake_case__ : int = False snake_case__ : Optional[Any] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) _lowerCamelCase : List[str] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] # compare the actual values for a slice. _lowerCamelCase : Union[str, Any] = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
83
1
"""simple docstring""" import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right lowerCAmelCase__ = 50003 lowerCAmelCase__ = 50002 @require_sentencepiece @require_tokenizers class __snake_case ( _lowercase , unittest.TestCase): snake_case__ : Tuple = PLBartTokenizer snake_case__ : Optional[int] = None snake_case__ : List[str] = False def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing _lowerCamelCase : Optional[int] = PLBartTokenizer(__lowerCAmelCase , language_codes='''base''' , keep_accents=__lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Optional[int] = PLBartTokenizer(__lowerCAmelCase , language_codes='''base''' , keep_accents=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__lowerCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) _lowerCamelCase : Optional[int] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) _lowerCamelCase : Union[str, Any] = tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) self.assertListEqual( __lowerCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) _lowerCamelCase : Any = tokenizer.convert_ids_to_tokens(__lowerCAmelCase ) self.assertListEqual( __lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) _lowerCamelCase : Dict = tokenizer.vocab_size _lowerCamelCase : Union[str, Any] = [tokenizer.convert_ids_to_tokens(__lowerCAmelCase ) for x in range(end - 4 , __lowerCAmelCase )] self.assertListEqual(__lowerCAmelCase , ['''__java__''', '''__python__''', '''__en_XX__''', '''<mask>'''] ) _lowerCamelCase : Tuple = '''java.lang.Exception, python.lang.Exception, javascript, php, ruby, go''' _lowerCamelCase : Any = tokenizer(__lowerCAmelCase ).input_ids self.assertEqual( tokenizer.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) , __lowerCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = PLBartTokenizer(__lowerCAmelCase , language_codes='''multi''' , keep_accents=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__lowerCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) _lowerCamelCase : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) _lowerCamelCase : Tuple = tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) self.assertListEqual( __lowerCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) _lowerCamelCase : Optional[int] = tokenizer.convert_ids_to_tokens(__lowerCAmelCase ) self.assertListEqual( __lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) _lowerCamelCase : str = tokenizer.vocab_size _lowerCamelCase : Any = [tokenizer.convert_ids_to_tokens(__lowerCAmelCase ) for x in range(end - 7 , __lowerCAmelCase )] self.assertListEqual( __lowerCAmelCase , ['''__java__''', '''__python__''', '''__en_XX__''', '''__javascript__''', '''__php__''', '''__ruby__''', '''__go__'''] ) _lowerCamelCase : Tuple = '''java.lang.Exception, python.lang.Exception, javascript, php, ruby, go''' _lowerCamelCase : Optional[Any] = tokenizer(__lowerCAmelCase ).input_ids self.assertEqual( tokenizer.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase ) , __lowerCAmelCase , ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): snake_case__ : Optional[Any] = "uclanlp/plbart-python-en_XX" snake_case__ : Optional[int] = [ "def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])", "def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])", ] snake_case__ : List[Any] = [ "Returns the maximum value of a b c.", "Sums the values of a b c.", ] snake_case__ : Union[str, Any] = [ 1_3_4, 5_4_5_2, 3_3_4_6_0, 3_3_4_4_1, 3_3_4_6_3, 3_3_4_6_5, 3_3_4_6_3, 3_3_4_4_9, 9_8_8, 2_0, 3_3_4_5_6, 1_9, 3_3_4_5_6, 7_7_1, 3_9, 4_2_5_8, 8_8_9, 3_3_1_8, 3_3_4_4_1, 3_3_4_6_3, 3_3_4_6_5, 3_3_4_6_3, 3_3_4_4_9, 2_4_7_1, 2, PYTHON_CODE, ] @classmethod def SCREAMING_SNAKE_CASE ( cls : List[str] ): """simple docstring""" _lowerCamelCase : PLBartTokenizer = PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes='''base''' , src_lang='''python''' , tgt_lang='''en_XX''' ) _lowerCamelCase : int = 1 return cls def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''__java__'''] , 5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''__python__'''] , 5_0_0_0_2 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''__en_XX__'''] , 5_0_0_0_3 ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Dict = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.assertIn(__lowerCAmelCase , self.tokenizer.all_special_ids ) _lowerCamelCase : List[Any] = [EN_CODE, 9_0_3_7, 3_3_4_4_2, 5_7, 7_5_2, 1_5_3, 1_4, 5_6, 1_8, 9, 2] _lowerCamelCase : str = self.tokenizer.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : int = ['''def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])''' * 2_0] self.assertIsInstance(src_text[0] , __lowerCAmelCase ) _lowerCamelCase : List[str] = 1_0 _lowerCamelCase : List[Any] = self.tokenizer(__lowerCAmelCase , max_length=__lowerCAmelCase , truncation=__lowerCAmelCase ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __lowerCAmelCase ) self.assertEqual(len(__lowerCAmelCase ) , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''__java__'''] ) , [5_0_0_0_4, 5_0_0_0_1] ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[str] = tempfile.mkdtemp() _lowerCamelCase : Optional[int] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = PLBartTokenizer.from_pretrained(__lowerCAmelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __lowerCAmelCase ) @require_torch def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : str = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowerCAmelCase , return_tensors='''pt''' ) _lowerCamelCase : int = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] ) self.assertEqual(batch.decoder_input_ids[1][0] , __lowerCAmelCase ) self.assertEqual(batch.decoder_input_ids[1][-1] , 2 ) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] ) @require_torch def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Any = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) _lowerCamelCase : Union[str, Any] = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual((2, 2_6) , batch.input_ids.shape ) self.assertEqual((2, 2_6) , batch.attention_mask.shape ) _lowerCamelCase : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __lowerCAmelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.tokenizer(self.src_text , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=3 , return_tensors='''pt''' ) _lowerCamelCase : str = self.tokenizer( text_target=self.tgt_text , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=1_0 , return_tensors='''pt''' ) _lowerCamelCase : Tuple = targets['''input_ids'''] _lowerCamelCase : Union[str, Any] = shift_tokens_right(__lowerCAmelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''java''' ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , { # A, test, EOS, en_XX '''input_ids''': [[1_5_0, 2_4_2, 2, 5_0_0_0_3]], '''attention_mask''': [[1, 1, 1, 1]], # java '''forced_bos_token_id''': 5_0_0_0_1, } , )
83
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = '''hf-internal-testing/tiny-random-bert''' lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''') lowerCAmelCase__ = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6''' class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = cached_file(__lowerCAmelCase , __lowerCAmelCase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__lowerCAmelCase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : Optional[int] = f.read() self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) self.assertTrue(os.path.isfile(__lowerCAmelCase ) ) # File is cached at the same place the second time. _lowerCamelCase : Tuple = cached_file(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Using a specific revision to test the full commit hash. _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''9b8c223''' ) self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): _lowerCamelCase : Optional[int] = cached_file('''tiny-random-bert''' , __lowerCAmelCase ) with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): _lowerCamelCase : str = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''aaaa''' ) with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : int = cached_file(__lowerCAmelCase , '''conf''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , '''conf''' ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : List[Any] = f.read() self.assertTrue(os.path.isfile(os.path.join(__lowerCAmelCase , '''.no_exist''' , __lowerCAmelCase , '''conf''' ) ) ) _lowerCamelCase : str = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = cached_file(__lowerCAmelCase , '''conf''' , local_files_only=__lowerCAmelCase , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Any = mock.Mock() _lowerCamelCase : Optional[Any] = 5_0_0 _lowerCamelCase : Dict = {} _lowerCamelCase : List[Any] = HTTPError _lowerCamelCase : int = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__lowerCAmelCase ) as mock_head: _lowerCamelCase : Union[str, Any] = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_connection_errors=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __lowerCAmelCase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase , revision='''ahaha''' ) _lowerCamelCase : Dict = get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase ) # The name is the cached name which is not very easy to test, so instead we load the content. _lowerCamelCase : Dict = json.loads(open(__lowerCAmelCase , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = Path(__lowerCAmelCase ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__lowerCAmelCase , '''a.txt''' ) , str(__lowerCAmelCase ) ) self.assertIsNone(get_file_from_repo(__lowerCAmelCase , '''b.txt''' ) )
83
1
"""simple docstring""" import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __snake_case ( _lowercase , _lowercase , _lowercase): @register_to_config def __init__( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : float , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : str , __lowerCAmelCase : bool = False , ): """simple docstring""" super().__init__() _lowerCamelCase : str = nn.Embedding(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Dict = nn.Embedding(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : str = False _lowerCamelCase : List[Any] = nn.Dropout(p=__lowerCAmelCase ) _lowerCamelCase : Tuple = TaConfig( vocab_size=__lowerCAmelCase , d_model=__lowerCAmelCase , num_heads=__lowerCAmelCase , d_kv=__lowerCAmelCase , d_ff=__lowerCAmelCase , dropout_rate=__lowerCAmelCase , feed_forward_proj=__lowerCAmelCase , is_decoder=__lowerCAmelCase , is_encoder_decoder=__lowerCAmelCase , ) _lowerCamelCase : Union[str, Any] = nn.ModuleList() for lyr_num in range(__lowerCAmelCase ): _lowerCamelCase : str = TaBlock(__lowerCAmelCase ) self.encoders.append(__lowerCAmelCase ) _lowerCamelCase : List[Any] = TaLayerNorm(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = nn.Dropout(p=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : int = self.token_embedder(__lowerCAmelCase ) _lowerCamelCase : List[Any] = encoder_input_tokens.shape[1] _lowerCamelCase : int = torch.arange(__lowerCAmelCase , device=encoder_input_tokens.device ) x += self.position_encoding(__lowerCAmelCase ) _lowerCamelCase : Any = self.dropout_pre(__lowerCAmelCase ) # inverted the attention mask _lowerCamelCase : List[str] = encoder_input_tokens.size() _lowerCamelCase : Optional[int] = self.get_extended_attention_mask(__lowerCAmelCase , __lowerCAmelCase ) for lyr in self.encoders: _lowerCamelCase : Union[str, Any] = lyr(__lowerCAmelCase , __lowerCAmelCase )[0] _lowerCamelCase : Any = self.layer_norm(__lowerCAmelCase ) return self.dropout_post(__lowerCAmelCase ), encoder_inputs_mask
83
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( _lowercase): snake_case__ : List[str] = "cvt" def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=3 , __lowerCAmelCase : List[str]=[7, 3, 3] , __lowerCAmelCase : int=[4, 2, 2] , __lowerCAmelCase : int=[2, 1, 1] , __lowerCAmelCase : str=[6_4, 1_9_2, 3_8_4] , __lowerCAmelCase : Dict=[1, 3, 6] , __lowerCAmelCase : Optional[Any]=[1, 2, 1_0] , __lowerCAmelCase : Dict=[4.0, 4.0, 4.0] , __lowerCAmelCase : Dict=[0.0, 0.0, 0.0] , __lowerCAmelCase : Union[str, Any]=[0.0, 0.0, 0.0] , __lowerCAmelCase : int=[0.0, 0.0, 0.1] , __lowerCAmelCase : Union[str, Any]=[True, True, True] , __lowerCAmelCase : str=[False, False, True] , __lowerCAmelCase : List[str]=["dw_bn", "dw_bn", "dw_bn"] , __lowerCAmelCase : List[Any]=[3, 3, 3] , __lowerCAmelCase : Dict=[1, 1, 1] , __lowerCAmelCase : str=[2, 2, 2] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Any=1E-12 , **__lowerCAmelCase : int , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : int = patch_sizes _lowerCamelCase : Optional[Any] = patch_stride _lowerCamelCase : str = patch_padding _lowerCamelCase : Any = embed_dim _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Dict = depth _lowerCamelCase : Optional[int] = mlp_ratio _lowerCamelCase : Any = attention_drop_rate _lowerCamelCase : Any = drop_rate _lowerCamelCase : Dict = drop_path_rate _lowerCamelCase : Optional[int] = qkv_bias _lowerCamelCase : int = cls_token _lowerCamelCase : int = qkv_projection_method _lowerCamelCase : Optional[Any] = kernel_qkv _lowerCamelCase : List[str] = padding_kv _lowerCamelCase : Tuple = stride_kv _lowerCamelCase : Union[str, Any] = padding_q _lowerCamelCase : Optional[Any] = stride_q _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps
83
1
"""simple docstring""" import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' _lowerCamelCase : int = SwinConfig() _lowerCamelCase : Dict = swin_name.split('''_''' ) _lowerCamelCase : List[Any] = name_split[1] _lowerCamelCase : List[Any] = int(name_split[4] ) _lowerCamelCase : str = int(name_split[3][-1] ) if model_size == "tiny": _lowerCamelCase : Dict = 96 _lowerCamelCase : Tuple = (2, 2, 6, 2) _lowerCamelCase : List[Any] = (3, 6, 12, 24) elif model_size == "small": _lowerCamelCase : Union[str, Any] = 96 _lowerCamelCase : List[Any] = (2, 2, 18, 2) _lowerCamelCase : str = (3, 6, 12, 24) elif model_size == "base": _lowerCamelCase : int = 1_28 _lowerCamelCase : List[str] = (2, 2, 18, 2) _lowerCamelCase : Tuple = (4, 8, 16, 32) else: _lowerCamelCase : Optional[int] = 1_92 _lowerCamelCase : Any = (2, 2, 18, 2) _lowerCamelCase : Tuple = (6, 12, 24, 48) if "in22k" in swin_name: _lowerCamelCase : Optional[int] = 2_18_41 else: _lowerCamelCase : Optional[int] = 10_00 _lowerCamelCase : str = '''huggingface/label-files''' _lowerCamelCase : str = '''imagenet-1k-id2label.json''' _lowerCamelCase : Any = json.load(open(hf_hub_download(A_, A_, repo_type='''dataset''' ), '''r''' ) ) _lowerCamelCase : Optional[int] = {int(A_ ): v for k, v in idalabel.items()} _lowerCamelCase : List[str] = idalabel _lowerCamelCase : int = {v: k for k, v in idalabel.items()} _lowerCamelCase : List[Any] = img_size _lowerCamelCase : int = num_classes _lowerCamelCase : Optional[int] = embed_dim _lowerCamelCase : Optional[int] = depths _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Union[str, Any] = window_size return config def snake_case_ ( A_ : int ): '''simple docstring''' if "patch_embed.proj" in name: _lowerCamelCase : Optional[int] = name.replace('''patch_embed.proj''', '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: _lowerCamelCase : Optional[int] = name.replace('''patch_embed.norm''', '''embeddings.norm''' ) if "layers" in name: _lowerCamelCase : str = '''encoder.''' + name if "attn.proj" in name: _lowerCamelCase : List[Any] = name.replace('''attn.proj''', '''attention.output.dense''' ) if "attn" in name: _lowerCamelCase : Dict = name.replace('''attn''', '''attention.self''' ) if "norm1" in name: _lowerCamelCase : List[Any] = name.replace('''norm1''', '''layernorm_before''' ) if "norm2" in name: _lowerCamelCase : List[Any] = name.replace('''norm2''', '''layernorm_after''' ) if "mlp.fc1" in name: _lowerCamelCase : List[str] = name.replace('''mlp.fc1''', '''intermediate.dense''' ) if "mlp.fc2" in name: _lowerCamelCase : Optional[int] = name.replace('''mlp.fc2''', '''output.dense''' ) if name == "norm.weight": _lowerCamelCase : Any = '''layernorm.weight''' if name == "norm.bias": _lowerCamelCase : Union[str, Any] = '''layernorm.bias''' if "head" in name: _lowerCamelCase : Dict = name.replace('''head''', '''classifier''' ) else: _lowerCamelCase : List[Any] = '''swin.''' + name return name def snake_case_ ( A_ : List[str], A_ : int ): '''simple docstring''' for key in orig_state_dict.copy().keys(): _lowerCamelCase : int = orig_state_dict.pop(A_ ) if "mask" in key: continue elif "qkv" in key: _lowerCamelCase : Optional[int] = key.split('''.''' ) _lowerCamelCase : Dict = int(key_split[1] ) _lowerCamelCase : Dict = int(key_split[3] ) _lowerCamelCase : List[Any] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _lowerCamelCase : Optional[Any] = val[:dim, :] _lowerCamelCase : int = val[ dim : dim * 2, : ] _lowerCamelCase : Optional[Any] = val[-dim:, :] else: _lowerCamelCase : Optional[int] = val[ :dim ] _lowerCamelCase : int = val[ dim : dim * 2 ] _lowerCamelCase : Union[str, Any] = val[ -dim: ] else: _lowerCamelCase : List[Any] = val return orig_state_dict def snake_case_ ( A_ : Any, A_ : Tuple ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = timm.create_model(A_, pretrained=A_ ) timm_model.eval() _lowerCamelCase : Union[str, Any] = get_swin_config(A_ ) _lowerCamelCase : Union[str, Any] = SwinForImageClassification(A_ ) model.eval() _lowerCamelCase : Tuple = convert_state_dict(timm_model.state_dict(), A_ ) model.load_state_dict(A_ ) _lowerCamelCase : Dict = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _lowerCamelCase : Optional[int] = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''', '''-''' ) ) ) _lowerCamelCase : str = Image.open(requests.get(A_, stream=A_ ).raw ) _lowerCamelCase : Tuple = image_processor(images=A_, return_tensors='''pt''' ) _lowerCamelCase : Dict = timm_model(inputs['''pixel_values'''] ) _lowerCamelCase : Union[str, Any] = model(**A_ ).logits assert torch.allclose(A_, A_, atol=1E-3 ) print(F'''Saving model {swin_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swin_name''', default='''swin_tiny_patch4_window7_224''', type=str, help='''Name of the Swin 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.''' ) lowerCAmelCase__ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
83
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __snake_case ( _lowercase): snake_case__ : torch.FloatTensor snake_case__ : torch.FloatTensor class __snake_case ( _lowercase , _lowercase): snake_case__ : int = 1 @register_to_config def __init__( self : str , __lowerCAmelCase : int = 2_0_0_0 , __lowerCAmelCase : float = 0.15 , __lowerCAmelCase : float = 0.01 , __lowerCAmelCase : float = 13_48.0 , __lowerCAmelCase : float = 1E-5 , __lowerCAmelCase : int = 1 , ): """simple docstring""" _lowerCamelCase : Optional[int] = sigma_max # setable values _lowerCamelCase : Dict = None self.set_sigmas(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : Union[str, torch.device] = None ): """simple docstring""" _lowerCamelCase : Tuple = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCamelCase : Optional[int] = torch.linspace(1 , __lowerCAmelCase , __lowerCAmelCase , device=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None ): """simple docstring""" _lowerCamelCase : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCamelCase : int = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCamelCase : Optional[int] = torch.exp(torch.linspace(math.log(__lowerCAmelCase ) , math.log(__lowerCAmelCase ) , __lowerCAmelCase ) ) _lowerCamelCase : Tuple = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : int , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) _lowerCamelCase : Tuple = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCamelCase : Dict = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCamelCase : Optional[int] = timesteps.to(self.discrete_sigmas.device ) _lowerCamelCase : Any = self.discrete_sigmas[timesteps].to(sample.device ) _lowerCamelCase : int = self.get_adjacent_sigma(__lowerCAmelCase , __lowerCAmelCase ).to(sample.device ) _lowerCamelCase : Any = torch.zeros_like(__lowerCAmelCase ) _lowerCamelCase : Any = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCamelCase : Union[str, Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): _lowerCamelCase : List[Any] = diffusion.unsqueeze(-1 ) _lowerCamelCase : int = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCamelCase : List[str] = randn_tensor( sample.shape , layout=sample.layout , generator=__lowerCAmelCase , device=sample.device , dtype=sample.dtype ) _lowerCamelCase : List[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCamelCase : int = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=__lowerCAmelCase , prev_sample_mean=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCamelCase : Union[str, Any] = randn_tensor(sample.shape , layout=sample.layout , generator=__lowerCAmelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr _lowerCamelCase : Union[str, Any] = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : str = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCamelCase : Tuple = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): _lowerCamelCase : str = step_size.unsqueeze(-1 ) _lowerCamelCase : Any = sample + step_size * model_output _lowerCamelCase : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , ): """simple docstring""" _lowerCamelCase : Dict = timesteps.to(original_samples.device ) _lowerCamelCase : Union[str, Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] _lowerCamelCase : Union[str, Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(__lowerCAmelCase ) * sigmas[:, None, None, None] ) _lowerCamelCase : int = noise + original_samples return noisy_samples def __len__( self : Optional[int] ): """simple docstring""" return self.config.num_train_timesteps
83
1
"""simple docstring""" # flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {} lowerCAmelCase__ = {} lowerCAmelCase__ = {} def snake_case_ ( A_ : type, A_ : Optional[str], A_ : Optional[List[str]] = None, ): '''simple docstring''' _lowerCamelCase : Optional[Any] = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( F'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})''' ) _lowerCamelCase : Optional[Any] = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( F'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})''' ) _lowerCamelCase : Dict = format_type def snake_case_ ( A_ : Exception, A_ : Optional[str], A_ : Optional[List[str]] = None ): '''simple docstring''' _lowerCamelCase : Optional[Any] = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): _lowerCamelCase : List[Any] = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=['''python''']) _register_formatter(ArrowFormatter, '''arrow''', aliases=['''pa''', '''pyarrow''']) _register_formatter(NumpyFormatter, '''numpy''', aliases=['''np''']) _register_formatter(PandasFormatter, '''pandas''', aliases=['''pd''']) _register_formatter(CustomFormatter, '''custom''') if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, '''torch''', aliases=['''pt''', '''pytorch''']) else: lowerCAmelCase__ = ValueError('''PyTorch needs to be installed to be able to return PyTorch tensors.''') _register_unavailable_formatter(_torch_error, '''torch''', aliases=['''pt''', '''pytorch''']) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, '''tensorflow''', aliases=['''tf''']) else: lowerCAmelCase__ = ValueError('''Tensorflow needs to be installed to be able to return Tensorflow tensors.''') _register_unavailable_formatter(_tf_error, '''tensorflow''', aliases=['''tf''']) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, '''jax''', aliases=[]) else: lowerCAmelCase__ = ValueError('''JAX needs to be installed to be able to return JAX arrays.''') _register_unavailable_formatter(_jax_error, '''jax''', aliases=[]) def snake_case_ ( A_ : Optional[str] ): '''simple docstring''' if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def snake_case_ ( A_ : Optional[str], **A_ : Dict ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = get_format_type_from_alias(A_ ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**A_ ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( F'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got \'{format_type}\'''' )
83
"""simple docstring""" from torch import nn def snake_case_ ( A_ : int ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'''Unsupported activation function: {act_fn}''' )
83
1
"""simple docstring""" import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __snake_case ( _lowercase): def __init__( self : Any , *__lowerCAmelCase : Any , __lowerCAmelCase : str=None , __lowerCAmelCase : Tuple=None , **__lowerCAmelCase : Any ): """simple docstring""" super().__init__(*__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = eval_examples _lowerCamelCase : Optional[int] = post_process_function def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : str=None , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : str = "eval" ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.eval_dataset if eval_dataset is None else eval_dataset _lowerCamelCase : Any = self.get_eval_dataloader(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _lowerCamelCase : Dict = self.compute_metrics _lowerCamelCase : str = None _lowerCamelCase : Union[str, Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _lowerCamelCase : List[Any] = time.time() try: _lowerCamelCase : Union[str, Any] = eval_loop( __lowerCAmelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCAmelCase , metric_key_prefix=__lowerCAmelCase , ) finally: _lowerCamelCase : int = compute_metrics _lowerCamelCase : List[str] = self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __lowerCAmelCase , __lowerCAmelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _lowerCamelCase : Optional[Any] = self.post_process_function(__lowerCAmelCase , __lowerCAmelCase , output.predictions ) _lowerCamelCase : Optional[int] = self.compute_metrics(__lowerCAmelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): _lowerCamelCase : Tuple = metrics.pop(__lowerCAmelCase ) metrics.update(output.metrics ) else: _lowerCamelCase : Tuple = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__lowerCAmelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _lowerCamelCase : str = self.callback_handler.on_evaluate(self.args , self.state , self.control , __lowerCAmelCase ) return metrics def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Any=None , __lowerCAmelCase : str = "test" ): """simple docstring""" _lowerCamelCase : Optional[int] = self.get_test_dataloader(__lowerCAmelCase ) # Temporarily disable metric computation, we will do it in the loop here. _lowerCamelCase : List[str] = self.compute_metrics _lowerCamelCase : List[Any] = None _lowerCamelCase : List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _lowerCamelCase : Any = time.time() try: _lowerCamelCase : str = eval_loop( __lowerCAmelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCAmelCase , metric_key_prefix=__lowerCAmelCase , ) finally: _lowerCamelCase : str = compute_metrics _lowerCamelCase : str = self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __lowerCAmelCase , __lowerCAmelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _lowerCamelCase : str = self.post_process_function(__lowerCAmelCase , __lowerCAmelCase , output.predictions , '''predict''' ) _lowerCamelCase : Tuple = self.compute_metrics(__lowerCAmelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): _lowerCamelCase : Tuple = metrics.pop(__lowerCAmelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__lowerCAmelCase )
83
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def snake_case_ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(F'''| 0 | 0 | {nor_gate(0, 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0, 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1, 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1, 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
83
1
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __snake_case ( _lowercase): snake_case__ : str = ["image_processor", "tokenizer"] snake_case__ : Tuple = "Pix2StructImageProcessor" snake_case__ : Dict = ("T5Tokenizer", "T5TokenizerFast") def __init__( self : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : str = False super().__init__(__lowerCAmelCase , __lowerCAmelCase ) def __call__( self : str , __lowerCAmelCase : Dict=None , __lowerCAmelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __lowerCAmelCase : bool = True , __lowerCAmelCase : Union[bool, str, PaddingStrategy] = False , __lowerCAmelCase : Union[bool, str, TruncationStrategy] = None , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Optional[int] = 2_0_4_8 , __lowerCAmelCase : int = 0 , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Optional[bool] = None , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = True , __lowerCAmelCase : Optional[Union[str, TensorType]] = None , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None and not self.image_processor.is_vqa: _lowerCamelCase : Any = self.tokenizer _lowerCamelCase : Dict = self.tokenizer( text=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , stride=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , return_overflowing_tokens=__lowerCAmelCase , return_special_tokens_mask=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , return_token_type_ids=__lowerCAmelCase , return_length=__lowerCAmelCase , verbose=__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values _lowerCamelCase : Any = self.image_processor( __lowerCAmelCase , return_tensors=__lowerCAmelCase , max_patches=__lowerCAmelCase , **__lowerCAmelCase ) else: # add pixel_values and bbox _lowerCamelCase : int = self.image_processor( __lowerCAmelCase , return_tensors=__lowerCAmelCase , max_patches=__lowerCAmelCase , header_text=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None and not self.image_processor.is_vqa: _lowerCamelCase : Optional[int] = self.tokenizer( text=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , stride=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , return_overflowing_tokens=__lowerCAmelCase , return_special_tokens_mask=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , return_token_type_ids=__lowerCAmelCase , return_length=__lowerCAmelCase , verbose=__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase , ) if "attention_mask" in text_encoding: _lowerCamelCase : Tuple = text_encoding.pop('''attention_mask''' ) if "input_ids" in text_encoding: _lowerCamelCase : Any = text_encoding.pop('''input_ids''' ) else: _lowerCamelCase : int = None if text_encoding is not None: encoding_image_processor.update(__lowerCAmelCase ) return encoding_image_processor def SCREAMING_SNAKE_CASE ( self : Tuple , *__lowerCAmelCase : str , **__lowerCAmelCase : Any ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[str] = self.tokenizer.model_input_names _lowerCamelCase : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
83
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : list[list[int]] ): '''simple docstring''' for i in range(1, len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(A_ ) ): for j in range(1, len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" from collections import defaultdict def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : List[Any] = 1 _lowerCamelCase : List[Any] = True for v in tree[start]: if v not in visited: ret += dfs(A_ ) if ret % 2 == 0: cuts.append(A_ ) return ret def snake_case_ ( ): '''simple docstring''' dfs(1 ) if __name__ == "__main__": lowerCAmelCase__ , lowerCAmelCase__ = 10, 9 lowerCAmelCase__ = defaultdict(list) lowerCAmelCase__ = {} lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = [(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)
83
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Optional[int] = data _lowerCamelCase : Node[T] | None = None def __str__( self : Optional[Any] ): """simple docstring""" return f'''{self.data}''' class __snake_case ( Generic[T]): def __init__( self : int ): """simple docstring""" _lowerCamelCase : Node[T] | None = None def __iter__( self : str ): """simple docstring""" _lowerCamelCase : List[str] = self.top while node: yield node.data _lowerCamelCase : Any = node.next def __str__( self : int ): """simple docstring""" return "->".join([str(__lowerCAmelCase ) for item in self] ) def __len__( self : int ): """simple docstring""" return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.top is None def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Tuple = Node(__lowerCAmelCase ) if not self.is_empty(): _lowerCamelCase : Optional[int] = self.top _lowerCamelCase : List[str] = node def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , __lowerCAmelCase ) _lowerCamelCase : Any = self.top _lowerCamelCase : Any = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = None if __name__ == "__main__": from doctest import testmod testmod()
83
1
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowerCAmelCase__ = '''\ @inproceedings{pillutla-etal:mauve:neurips2021, title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers}, author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid}, booktitle = {NeurIPS}, year = {2021} } ''' lowerCAmelCase__ = '''\ MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure. MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences. For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021). This metrics is a wrapper around the official implementation of MAUVE: https://github.com/krishnap25/mauve ''' lowerCAmelCase__ = ''' Calculates MAUVE scores between two lists of generated text and reference text. Args: predictions: list of generated text to score. Each predictions should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. Optional Args: num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1 kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9 kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5 kmeans_max_iter: maximum number of k-means iterations. Default 500 featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\']. device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU max_text_length: maximum number of tokens to consider. Default 1024 divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25 mauve_scaling_factor: "c" from the paper. Default 5. verbose: If True (default), print running time updates seed: random seed to initialize k-means cluster assignments. Returns: mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer, frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer, divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve, p_hist: a discrete distribution, which is a quantized version of the text distribution p_text, q_hist: same as above, but with q_text. Examples: >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest >>> import datasets >>> mauve = datasets.load_metric(\'mauve\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP >>> print(out.mauve) # doctest: +SKIP 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __snake_case ( datasets.Metric): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : str=None , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : Optional[int]="auto" , __lowerCAmelCase : List[Any]=-1 , __lowerCAmelCase : Optional[int]=0.9 , __lowerCAmelCase : str=5 , __lowerCAmelCase : Dict=5_0_0 , __lowerCAmelCase : Any="gpt2-large" , __lowerCAmelCase : Union[str, Any]=-1 , __lowerCAmelCase : Optional[Any]=1_0_2_4 , __lowerCAmelCase : str=2_5 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : str=2_5 , ): """simple docstring""" _lowerCamelCase : int = compute_mauve( p_text=__lowerCAmelCase , q_text=__lowerCAmelCase , p_features=__lowerCAmelCase , q_features=__lowerCAmelCase , p_tokens=__lowerCAmelCase , q_tokens=__lowerCAmelCase , num_buckets=__lowerCAmelCase , pca_max_data=__lowerCAmelCase , kmeans_explained_var=__lowerCAmelCase , kmeans_num_redo=__lowerCAmelCase , kmeans_max_iter=__lowerCAmelCase , featurize_model_name=__lowerCAmelCase , device_id=__lowerCAmelCase , max_text_length=__lowerCAmelCase , divergence_curve_discretization_size=__lowerCAmelCase , mauve_scaling_factor=__lowerCAmelCase , verbose=__lowerCAmelCase , seed=__lowerCAmelCase , ) return out
83
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase__ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCAmelCase__ = spec.loader.load_module() lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCAmelCase__ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = [] for config_class in list(CONFIG_MAPPING.values() ): _lowerCamelCase : Tuple = False # source code of `config_class` _lowerCamelCase : int = inspect.getsource(A_ ) _lowerCamelCase : str = _re_checkpoint.findall(A_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` _lowerCamelCase , _lowerCamelCase : Tuple = checkpoint # verify the checkpoint name corresponds to the checkpoint link _lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _lowerCamelCase : Union[str, Any] = True break _lowerCamelCase : Tuple = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
83
1
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black lowerCAmelCase__ = 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. lowerCAmelCase__ = ''' \""" 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 __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Any = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) _lowerCamelCase : Union[str, Any] = self.diffusers_dir shutil.copy( os.path.join(__lowerCAmelCase , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Optional[int] = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int]=None ): """simple docstring""" _lowerCamelCase : Tuple = comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: _lowerCamelCase : Union[str, Any] = comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result _lowerCamelCase : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 ) _lowerCamelCase : Any = black.format_str(__lowerCAmelCase , mode=__lowerCAmelCase ) _lowerCamelCase : Any = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(__lowerCAmelCase , '''w''' , newline='''\n''' ) as f: f.write(__lowerCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__lowerCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__lowerCAmelCase ) with open(__lowerCAmelCase , '''r''' ) as f: self.assertTrue(f.read() , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : List[Any] = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" 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''' , __lowerCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , __lowerCAmelCase ) , ) # Copy consistency with a really long name _lowerCamelCase : List[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''' , __lowerCAmelCase , __lowerCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , __lowerCAmelCase , overwrite_result=re.sub('''DDPM''' , '''Test''' , __lowerCAmelCase ) , )
83
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class __snake_case ( unittest.TestCase): pass @nightly @require_torch_gpu class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : int = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : str = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Dict = torch.manual_seed(0 ) _lowerCamelCase : List[Any] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : int = generator.manual_seed(0 ) _lowerCamelCase : List[str] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Optional[int] = torch.manual_seed(0 ) _lowerCamelCase : int = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images _lowerCamelCase : List[str] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Dict = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
83
1
"""simple docstring""" from collections import namedtuple lowerCAmelCase__ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase__ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def snake_case_ ( A_ : float, A_ : str, A_ : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ''', '''.join(A_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ''', '''.join(A_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = '''1''' lowerCAmelCase__ = '''0''' lowerCAmelCase__ = '''1''' lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('''Create inference session...''') lowerCAmelCase__ = ['''TensorrtExecutionProvider''', '''CUDAExecutionProvider'''] lowerCAmelCase__ = ort.InferenceSession('''model.onnx''', sess_options=sess_opt, providers=execution_provider) lowerCAmelCase__ = ort.RunOptions() lowerCAmelCase__ = 128 lowerCAmelCase__ = 1 lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) print('''Warm up phase...''') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Start inference...''') lowerCAmelCase__ = time.time() lowerCAmelCase__ = 2000 lowerCAmelCase__ = {} for iter in range(max_iters): lowerCAmelCase__ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Average Inference Time = {:.3f} ms'''.format((time.time() - start_time) * 1000 / max_iters))
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = {'''configuration_wavlm''': ['''WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WavLMConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WavLMForAudioFrameClassification''', '''WavLMForCTC''', '''WavLMForSequenceClassification''', '''WavLMForXVector''', '''WavLMModel''', '''WavLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" import colorsys from PIL import Image # type: ignore def snake_case_ ( A_ : float, A_ : float, A_ : int ): '''simple docstring''' _lowerCamelCase : List[Any] = x _lowerCamelCase : List[Any] = y for step in range(A_ ): # noqa: B007 _lowerCamelCase : Dict = a * a - b * b + x _lowerCamelCase : List[str] = 2 * a * b + y _lowerCamelCase : Any = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(A_, 1, 1 ) ) def snake_case_ ( A_ : int = 8_00, A_ : int = 6_00, A_ : float = -0.6, A_ : float = 0, A_ : float = 3.2, A_ : int = 50, A_ : bool = True, ): '''simple docstring''' _lowerCamelCase : Tuple = Image.new('''RGB''', (image_width, image_height) ) _lowerCamelCase : int = img.load() # loop through the image-coordinates for image_x in range(A_ ): for image_y in range(A_ ): # determine the figure-coordinates based on the image-coordinates _lowerCamelCase : Optional[Any] = figure_width / image_width * image_height _lowerCamelCase : List[Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width _lowerCamelCase : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height _lowerCamelCase : str = get_distance(A_, A_, A_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: _lowerCamelCase : Dict = get_color_coded_rgb(A_ ) else: _lowerCamelCase : str = get_black_and_white_rgb(A_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCAmelCase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ): '''simple docstring''' _lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {} _lowerCamelCase : Union[str, Any] = padding_side return tokenizer( [line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, ) def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ): '''simple docstring''' _lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ): """simple docstring""" super().__init__() _lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' ) _lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' ) _lowerCamelCase : List[Any] = self.get_char_lens(self.src_file ) _lowerCamelCase : Optional[int] = max_source_length _lowerCamelCase : Optional[Any] = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _lowerCamelCase : List[Any] = tokenizer _lowerCamelCase : List[Any] = prefix if n_obs is not None: _lowerCamelCase : List[str] = self.src_lens[:n_obs] _lowerCamelCase : int = src_lang _lowerCamelCase : Union[str, Any] = tgt_lang def __len__( self : int ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = index + 1 # linecache starts at 1 _lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' ) _lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowerCAmelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _lowerCamelCase : Optional[int] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer ) _lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' ) _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' ) _lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze() _lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() _lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ): """simple docstring""" return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) _lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowerCAmelCase__ = getLogger(__name__) def snake_case_ ( A_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(A_ ) ) def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Dict = get_git_info() save_json(A_, os.path.join(A_, '''git_log.json''' ) ) def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ): '''simple docstring''' with open(A_, '''w''' ) as f: json.dump(A_, A_, indent=A_, **A_ ) def snake_case_ ( A_ : Any ): '''simple docstring''' with open(A_ ) as f: return json.load(A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ ) _lowerCamelCase : str = { '''repo_id''': str(A_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case_ ( A_ : Callable, A_ : Iterable ): '''simple docstring''' return list(map(A_, A_ ) ) def snake_case_ ( A_ : str, A_ : Tuple ): '''simple docstring''' with open(A_, '''wb''' ) as f: return pickle.dump(A_, A_ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' def remove_articles(A_ : str ): return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ ) def white_space_fix(A_ : Any ): return " ".join(text.split() ) def remove_punc(A_ : List[Any] ): _lowerCamelCase : Any = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case_ ( A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : str = normalize_answer(A_ ).split() _lowerCamelCase : int = normalize_answer(A_ ).split() _lowerCamelCase : str = Counter(A_ ) & Counter(A_ ) _lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 _lowerCamelCase : int = 1.0 * num_same / len(A_ ) _lowerCamelCase : str = 1.0 * num_same / len(A_ ) _lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case_ ( A_ : Dict, A_ : str ): '''simple docstring''' return normalize_answer(A_ ) == normalize_answer(A_ ) def snake_case_ ( A_ : List[str], A_ : List[str] ): '''simple docstring''' assert len(A_ ) == len(A_ ) _lowerCamelCase : Optional[Any] = 0 for hypo, pred in zip(A_, A_ ): em += exact_match_score(A_, A_ ) if len(A_ ) > 0: em /= len(A_ ) return {"em": em} def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Dict = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _lowerCamelCase : Tuple = '''dropout_rate''' for p in extra_params: if getattr(A_, A_, A_ ): if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) ) delattr(A_, A_ ) continue _lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p] setattr(A_, A_, getattr(A_, A_ ) ) delattr(A_, A_ ) return hparams, config
83
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=_lowercase): snake_case__ : Optional[Any] = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : List[Any] ): """simple docstring""" requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , *__lowerCAmelCase : str , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : int , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
83
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "camembert" def __init__( self : Optional[Any] , __lowerCAmelCase : Any=3_0_5_2_2 , __lowerCAmelCase : List[str]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Optional[int]=5_1_2 , __lowerCAmelCase : str=2 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : List[Any]=1E-12 , __lowerCAmelCase : Union[str, Any]=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : str="absolute" , __lowerCAmelCase : Any=True , __lowerCAmelCase : Optional[int]=None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Optional[Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : List[str] = classifier_dropout class __snake_case ( _lowercase): @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
83
1
"""simple docstring""" import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = '''https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg''' _lowerCamelCase : str = Image.open(requests.get(A_, stream=A_ ).raw ).convert('''RGB''' ) return image def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Optional[Any] = [] # fmt: off # vision encoder rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') ) rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') ) rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') ) rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.embeddings.layernorm.weight''') ) rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.embeddings.layernorm.bias''') ) # fmt: on return rename_keys def snake_case_ ( A_ : str, A_ : Optional[Any], A_ : Dict ): '''simple docstring''' _lowerCamelCase : List[Any] = dct.pop(A_ ) _lowerCamelCase : Dict = val def snake_case_ ( A_ : List[Any], A_ : List[Any] ): '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases _lowerCamelCase : Tuple = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) _lowerCamelCase : Any = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict _lowerCamelCase : Union[str, Any] = torch.cat((q_bias, torch.zeros_like(A_, requires_grad=A_ ), v_bias) ) _lowerCamelCase : Any = qkv_bias def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : Tuple = 3_64 if '''coco''' in model_name else 2_24 _lowerCamelCase : Optional[int] = InstructBlipVisionConfig(image_size=A_ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: _lowerCamelCase : List[str] = TaConfig.from_pretrained('''google/flan-t5-xl''', dense_act_fn='''gelu''', bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: _lowerCamelCase : int = TaConfig.from_pretrained('''google/flan-t5-xxl''', dense_act_fn='''gelu''', bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: _lowerCamelCase : int = LlamaConfig.from_pretrained('''decapoda-research/llama-7b-hf''', vocab_size=3_20_01 ).to_dict() elif "vicuna-13b" in model_name: _lowerCamelCase : Dict = LlamaConfig.from_pretrained('''decapoda-research/llama-13b-hf''', vocab_size=3_20_01 ).to_dict() else: raise ValueError('''Model name not supported''' ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 _lowerCamelCase : Any = InstructBlipQFormerConfig(vocab_size=3_05_23 ).to_dict() _lowerCamelCase : List[Any] = InstructBlipConfig(vision_config=A_, text_config=A_, qformer_config=A_ ) return config, image_size @torch.no_grad() def snake_case_ ( A_ : str, A_ : Any=None, A_ : str=False ): '''simple docstring''' _lowerCamelCase : Dict = AutoTokenizer.from_pretrained('''bert-base-uncased''', truncation_side='''left''' ) qformer_tokenizer.add_special_tokens({'''bos_token''': '''[DEC]'''} ) if "t5" in model_name: _lowerCamelCase : Dict = TaTokenizerFast.from_pretrained('''google/flan-t5-xl''', truncation_side='''left''' ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) _lowerCamelCase : Optional[int] = LlamaTokenizerFast.from_pretrained( '''huggyllama/llama-7b''', truncation_side='''left''', bos_token='''</s>''', unk_token='''</s>''' ) tokenizer.add_special_tokens({'''pad_token''': '''[PAD]'''} ) _lowerCamelCase , _lowerCamelCase : Dict = get_blipa_config(A_ ) _lowerCamelCase : Dict = InstructBlipForConditionalGeneration(A_ ).eval() _lowerCamelCase : Optional[int] = { '''instructblip-vicuna-7b''': ('''blip2_vicuna_instruct''', '''vicuna7b'''), '''instructblip-vicuna-13b''': ('''blip2_vicuna_instruct''', '''vicuna13b'''), '''instructblip-flan-t5-xl''': ('''blip2_t5_instruct''', '''flant5xl'''), '''instructblip-flan-t5-xxl''': ('''blip2_t5_instruct''', '''flant5xxl'''), } _lowerCamelCase , _lowerCamelCase : Any = model_name_to_original[model_name] # load original model print('''Loading original model...''' ) _lowerCamelCase : Tuple = '''cuda:1''' if torch.cuda.is_available() else '''cpu''' _lowerCamelCase : Dict = '''cuda:2''' if torch.cuda.is_available() else '''cpu''' _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : str = load_model_and_preprocess( name=A_, model_type=A_, is_eval=A_, device=A_ ) original_model.eval() print('''Done!''' ) # update state dict keys _lowerCamelCase : Tuple = original_model.state_dict() _lowerCamelCase : Tuple = create_rename_keys(A_ ) for src, dest in rename_keys: rename_key(A_, A_, A_ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): _lowerCamelCase : Tuple = state_dict.pop(A_ ) if key.startswith('''Qformer.bert''' ): _lowerCamelCase : str = key.replace('''Qformer.bert''', '''qformer''' ) if "attention.self" in key: _lowerCamelCase : List[Any] = key.replace('''self''', '''attention''' ) if "llm_proj" in key: _lowerCamelCase : Dict = key.replace('''llm_proj''', '''language_projection''' ) if "t5_proj" in key: _lowerCamelCase : List[Any] = key.replace('''t5_proj''', '''language_projection''' ) if key.startswith('''llm_model''' ): _lowerCamelCase : Optional[int] = key.replace('''llm_model''', '''language_model''' ) if key.startswith('''t5''' ): _lowerCamelCase : List[Any] = key.replace('''t5''', '''language''' ) _lowerCamelCase : List[Any] = val # read in qv biases read_in_q_v_bias(A_, A_ ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(A_, strict=A_ ) _lowerCamelCase : str = load_demo_image() _lowerCamelCase : Union[str, Any] = '''What is unusual about this image?''' # create processor _lowerCamelCase : Tuple = BlipImageProcessor( size={'''height''': image_size, '''width''': image_size}, image_mean=A_, image_std=A_ ) _lowerCamelCase : List[str] = InstructBlipProcessor( image_processor=A_, tokenizer=A_, qformer_tokenizer=A_, ) _lowerCamelCase : Dict = processor(images=A_, text=A_, return_tensors='''pt''' ).to(A_ ) # make sure processor creates exact same pixel values _lowerCamelCase : Optional[Any] = vis_processors['''eval'''](A_ ).unsqueeze(0 ).to(A_ ) _lowerCamelCase : List[Any] = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ), A_ ) original_model.to(A_ ) hf_model.to(A_ ) with torch.no_grad(): if "vicuna" in model_name: _lowerCamelCase : List[Any] = original_model({'''image''': original_pixel_values, '''text_input''': [prompt]} ).logits _lowerCamelCase : List[Any] = hf_model(**A_ ).logits else: _lowerCamelCase : Tuple = original_model( {'''image''': original_pixel_values, '''text_input''': [prompt], '''text_output''': ['''\n''']} ).logits _lowerCamelCase : str = tokenizer('''\n''', return_tensors='''pt''' ).input_ids.to(A_ ) _lowerCamelCase : Optional[Any] = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id, -1_00 ) _lowerCamelCase : Any = hf_model(**A_, labels=A_ ).logits print('''First values of original logits:''', original_logits[0, :3, :3] ) print('''First values of HF logits:''', logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape _lowerCamelCase : Tuple = 1E-4 if '''vicuna''' in model_name else 1E-5 assert torch.allclose(original_logits.to(logits.device ), A_, atol=A_ ) print('''Looks ok!''' ) print('''Generating with original model...''' ) _lowerCamelCase : str = original_model.generate({'''image''': original_pixel_values, '''prompt''': prompt}, num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print('''Generating with HF model...''' ) _lowerCamelCase : Tuple = hf_model.generate( **A_, do_sample=A_, num_beams=5, max_length=2_56, min_length=1, top_p=0.9, repetition_penalty=1.5, length_penalty=1.0, temperature=1, ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? _lowerCamelCase : Union[str, Any] = 2 print('''Original generation:''', A_ ) _lowerCamelCase : Dict = processor.batch_decode(A_, skip_special_tokens=A_ ) _lowerCamelCase : str = [text.strip() for text in output_text] print('''HF generation:''', A_ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(A_ ) hf_model.save_pretrained(A_ ) if push_to_hub: processor.push_to_hub(F'''Salesforce/{model_name}''' ) hf_model.push_to_hub(F'''Salesforce/{model_name}''' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() lowerCAmelCase__ = [ '''instructblip-vicuna-7b''', '''instructblip-vicuna-13b''', '''instructblip-flan-t5-xl''', '''instructblip-flan-t5-xxl''', ] parser.add_argument( '''--model_name''', default='''instructblip-flan-t5-xl''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub after converting''', ) lowerCAmelCase__ = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
83
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowerCAmelCase__ = '''<<<<<<< This should probably be modified because it mentions: ''' lowerCAmelCase__ = '''======= >>>>>>> ''' lowerCAmelCase__ = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] lowerCAmelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def snake_case_ ( A_ : Namespace ): '''simple docstring''' return ConvertCommand(args.tfds_path, args.datasets_directory ) class __snake_case ( _lowercase): @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : ArgumentParser ): """simple docstring""" _lowerCamelCase : List[str] = parser.add_parser( '''convert''' , help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.''' , ) train_parser.add_argument( '''--tfds_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.''' , ) train_parser.add_argument( '''--datasets_directory''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the HuggingFace Datasets folder.''' ) train_parser.set_defaults(func=__lowerCAmelCase ) def __init__( self : str , __lowerCAmelCase : str , __lowerCAmelCase : str , *__lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = get_logger('''datasets-cli/converting''' ) _lowerCamelCase : int = tfds_path _lowerCamelCase : Dict = datasets_directory def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if os.path.isdir(self._tfds_path ): _lowerCamelCase : Union[str, Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): _lowerCamelCase : Dict = os.path.dirname(self._tfds_path ) else: raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.''' ) _lowerCamelCase : int = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) _lowerCamelCase : str = [] _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Union[str, Any] = {} if os.path.isdir(self._tfds_path ): _lowerCamelCase : List[str] = os.listdir(__lowerCAmelCase ) else: _lowerCamelCase : Optional[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) _lowerCamelCase : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not os.path.isfile(__lowerCAmelCase ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('''Skipping file''' ) continue with open(__lowerCAmelCase , encoding='''utf-8''' ) as f: _lowerCamelCase : Tuple = f.readlines() _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Union[str, Any] = False _lowerCamelCase : int = False _lowerCamelCase : Tuple = [] for line in lines: _lowerCamelCase : Optional[int] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: _lowerCamelCase : Union[str, Any] = '''import datasets\n''' elif "import tensorflow" in out_line: # order is important here _lowerCamelCase : List[str] = '''''' continue elif "from absl import logging" in out_line: _lowerCamelCase : str = '''from datasets import logging\n''' elif "getLogger" in out_line: _lowerCamelCase : Union[str, Any] = out_line.replace('''getLogger''' , '''get_logger''' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): _lowerCamelCase : Dict = True _lowerCamelCase : Optional[int] = list(filter(lambda __lowerCAmelCase : e in out_line , __lowerCAmelCase ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(__lowerCAmelCase ) + '''\n''' ) out_lines.append(__lowerCAmelCase ) out_lines.append(__lowerCAmelCase ) continue else: for pattern, replacement in TO_CONVERT: _lowerCamelCase : str = re.sub(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: _lowerCamelCase : Dict = re.match(R'''from\stensorflow_datasets.*import\s([^\.\r\n]+)''' , __lowerCAmelCase ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(''',''' ) ) _lowerCamelCase : Union[str, Any] = '''from . import ''' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: _lowerCamelCase : Any = True out_lines.append(__lowerCAmelCase ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset _lowerCamelCase : Union[str, Any] = f_name.replace('''.py''' , '''''' ) _lowerCamelCase : List[str] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(__lowerCAmelCase ) if needs_manual_update: with_manual_update.append(__lowerCAmelCase ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.writelines(__lowerCAmelCase ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: _lowerCamelCase : Optional[int] = os.path.basename(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = imports_to_builder_map[f_name.replace('''.py''' , '''''' )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(__lowerCAmelCase , __lowerCAmelCase ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
83
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''vocab_file''': '''vocab.txt'''} lowerCAmelCase__ = { '''vocab_file''': { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''', } } lowerCAmelCase__ = { '''YituTech/conv-bert-base''': 512, '''YituTech/conv-bert-medium-small''': 512, '''YituTech/conv-bert-small''': 512, } lowerCAmelCase__ = { '''YituTech/conv-bert-base''': {'''do_lower_case''': True}, '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True}, '''YituTech/conv-bert-small''': {'''do_lower_case''': True}, } class __snake_case ( _lowercase): snake_case__ : List[str] = VOCAB_FILES_NAMES snake_case__ : int = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[str] = PRETRAINED_INIT_CONFIGURATION snake_case__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Optional[int] = ConvBertTokenizer def __init__( self : Dict , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Any=True , __lowerCAmelCase : Dict="[UNK]" , __lowerCAmelCase : Any="[SEP]" , __lowerCAmelCase : Dict="[PAD]" , __lowerCAmelCase : Any="[CLS]" , __lowerCAmelCase : Tuple="[MASK]" , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : Dict=None , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" super().__init__( __lowerCAmelCase , tokenizer_file=__lowerCAmelCase , do_lower_case=__lowerCAmelCase , unk_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , tokenize_chinese_chars=__lowerCAmelCase , strip_accents=__lowerCAmelCase , **__lowerCAmelCase , ) _lowerCamelCase : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __lowerCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __lowerCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __lowerCAmelCase ) != tokenize_chinese_chars ): _lowerCamelCase : int = getattr(__lowerCAmelCase , normalizer_state.pop('''type''' ) ) _lowerCamelCase : Tuple = do_lower_case _lowerCamelCase : str = strip_accents _lowerCamelCase : List[str] = tokenize_chinese_chars _lowerCamelCase : Dict = normalizer_class(**__lowerCAmelCase ) _lowerCamelCase : str = do_lower_case def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any]=None ): """simple docstring""" _lowerCamelCase : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ): """simple docstring""" _lowerCamelCase : Optional[int] = [self.sep_token_id] _lowerCamelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[str] = None ): """simple docstring""" _lowerCamelCase : List[Any] = self._tokenizer.model.save(__lowerCAmelCase , name=__lowerCAmelCase ) return tuple(__lowerCAmelCase )
83
"""simple docstring""" def snake_case_ ( A_ : list, A_ : list, A_ : int, A_ : int, A_ : int ): '''simple docstring''' if index == number_of_items: return 0 _lowerCamelCase : int = 0 _lowerCamelCase : str = 0 _lowerCamelCase : Dict = knapsack(A_, A_, A_, A_, index + 1 ) if weights[index] <= max_weight: _lowerCamelCase : Tuple = values[index] + knapsack( A_, A_, A_, max_weight - weights[index], index + 1 ) return max(A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import math import unittest def snake_case_ ( A_ : int ): '''simple docstring''' assert isinstance(A_, A_ ) and ( number >= 0 ), "'number' must been an int and positive" 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 class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(1_1 ) ) self.assertTrue(is_prime(1_3 ) ) self.assertTrue(is_prime(1_7 ) ) self.assertTrue(is_prime(1_9 ) ) self.assertTrue(is_prime(2_3 ) ) self.assertTrue(is_prime(2_9 ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with self.assertRaises(__lowerCAmelCase ): is_prime(-1_9 ) self.assertFalse( is_prime(0 ) , '''Zero doesn\'t have any positive factors, primes must have exactly two.''' , ) self.assertFalse( is_prime(1 ) , '''One only has 1 positive factor, primes must have exactly two.''' , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
83
"""simple docstring""" from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=_lowercase): snake_case__ : Optional[Any] = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : List[Any] ): """simple docstring""" requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , *__lowerCAmelCase : str , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : int , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
83
1
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def snake_case_ ( A_ : str, A_ : str, A_ : str, A_ : PreTrainedTokenizer, A_ : int, A_ : Optional[int] = None, ): '''simple docstring''' _lowerCamelCase : Dict = {} if train_file is not None: _lowerCamelCase : Union[str, Any] = [train_file] if eval_file is not None: _lowerCamelCase : List[str] = [eval_file] if test_file is not None: _lowerCamelCase : Any = [test_file] _lowerCamelCase : str = datasets.load_dataset('''csv''', data_files=A_ ) _lowerCamelCase : Dict = list(ds[list(files.keys() )[0]].features.keys() ) _lowerCamelCase : List[str] = features_name.pop(A_ ) _lowerCamelCase : List[str] = list(set(ds[list(files.keys() )[0]][label_name] ) ) _lowerCamelCase : Tuple = {label: i for i, label in enumerate(A_ )} _lowerCamelCase : Optional[Any] = tokenizer.model_input_names _lowerCamelCase : Union[str, Any] = {} if len(A_ ) == 1: for k in files.keys(): _lowerCamelCase : int = ds[k].map( lambda A_ : tokenizer.batch_encode_plus( example[features_name[0]], truncation=A_, max_length=A_, padding='''max_length''' ), batched=A_, ) elif len(A_ ) == 2: for k in files.keys(): _lowerCamelCase : int = ds[k].map( lambda A_ : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]), truncation=A_, max_length=A_, padding='''max_length''', ), batched=A_, ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: _lowerCamelCase : List[Any] = {k: v for k, v in ex.items() if k in input_names} _lowerCamelCase : Tuple = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: _lowerCamelCase : Union[str, Any] = {k: v for k, v in ex.items() if k in input_names} _lowerCamelCase : Any = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: _lowerCamelCase : List[str] = {k: v for k, v in ex.items() if k in input_names} _lowerCamelCase : Any = labelaid[ex[label_name]] yield (d, label) _lowerCamelCase : str = ( tf.data.Dataset.from_generator( A_, ({k: tf.intaa for k in input_names}, tf.intaa), ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )), ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: _lowerCamelCase : Optional[Any] = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) _lowerCamelCase : List[Any] = ( tf.data.Dataset.from_generator( A_, ({k: tf.intaa for k in input_names}, tf.intaa), ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )), ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: _lowerCamelCase : Union[str, Any] = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) _lowerCamelCase : List[Any] = ( tf.data.Dataset.from_generator( A_, ({k: tf.intaa for k in input_names}, tf.intaa), ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )), ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: _lowerCamelCase : Tuple = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid lowerCAmelCase__ = logging.getLogger(__name__) @dataclass class __snake_case : snake_case__ : int = field(metadata={"help": "Which column contains the label"}) snake_case__ : str = field(default=_lowercase , metadata={"help": "The path of the training file"}) snake_case__ : Optional[str] = field(default=_lowercase , metadata={"help": "The path of the development file"}) snake_case__ : Optional[str] = field(default=_lowercase , metadata={"help": "The path of the test file"}) snake_case__ : int = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ : bool = field( default=_lowercase , metadata={"help": "Overwrite the cached training and evaluation sets"}) @dataclass class __snake_case : snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=_lowercase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=_lowercase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) snake_case__ : bool = field(default=_lowercase , metadata={"help": "Set this flag to use fast tokenization."}) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ : Optional[str] = field( default=_lowercase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) logger.info( F'''n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ''' F'''16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : Optional[Any] = 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, ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = get_tfds( train_file=data_args.train_file, eval_file=data_args.dev_file, test_file=data_args.test_file, tokenizer=A_, label_column_id=data_args.label_column_id, max_seq_length=data_args.max_seq_length, ) _lowerCamelCase : int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=len(A_ ), labelaid=A_, idalabel={id: label for label, id in labelaid.items()}, finetuning_task='''text-classification''', cache_dir=model_args.cache_dir, ) with training_args.strategy.scope(): _lowerCamelCase : Union[str, Any] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path, from_pt=bool('''.bin''' in model_args.model_name_or_path ), config=A_, cache_dir=model_args.cache_dir, ) def compute_metrics(A_ : EvalPrediction ) -> Dict: _lowerCamelCase : Dict = np.argmax(p.predictions, axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer _lowerCamelCase : Tuple = TFTrainer( model=A_, args=A_, train_dataset=A_, eval_dataset=A_, compute_metrics=A_, ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _lowerCamelCase : Tuple = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _lowerCamelCase : List[str] = trainer.evaluate() _lowerCamelCase : List[Any] = os.path.join(training_args.output_dir, '''eval_results.txt''' ) with open(A_, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(F''' {key} = {value}''' ) writer.write(F'''{key} = {value}\n''' ) results.update(A_ ) return results if __name__ == "__main__": main()
83
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __snake_case ( unittest.TestCase): @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Union[str, Any] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids _lowerCamelCase : Optional[int] = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids _lowerCamelCase : List[Any] = shift_tokens_right(__lowerCAmelCase , model.config.pad_token_id , model.config.decoder_start_token_id ) _lowerCamelCase : int = model(__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase ).logits _lowerCamelCase : Optional[Any] = optax.softmax_cross_entropy(__lowerCAmelCase , onehot(__lowerCAmelCase , logits.shape[-1] ) ).mean() _lowerCamelCase : Dict = -(labels.shape[-1] * loss.item()) _lowerCamelCase : Dict = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
83
1
"""simple docstring""" from math import isqrt def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : int = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, A_, A_ ): _lowerCamelCase : Tuple = False return [i for i in range(2, A_ ) if is_prime[i]] def snake_case_ ( A_ : int = 10**8 ): '''simple docstring''' _lowerCamelCase : Dict = calculate_prime_numbers(max_number // 2 ) _lowerCamelCase : Tuple = 0 _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : List[str] = len(A_ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F"""{solution() = }""")
83
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''', [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ], ) def snake_case_ ( A_ : Dict, A_ : List[str] ): '''simple docstring''' _lowerCamelCase : int = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''', '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) _lowerCamelCase : str = DatasetInfosDict.from_directory(A_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''', [ DatasetInfo(), DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ), ], ) def snake_case_ ( A_ : str, A_ : DatasetInfo ): '''simple docstring''' _lowerCamelCase : Optional[Any] = str(A_ ) dataset_info.write_to_directory(A_ ) _lowerCamelCase : str = DatasetInfo.from_directory(A_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(A_, '''dataset_info.json''' ) ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = DatasetInfo( description='''foo''', citation='''bar''', homepage='''https://foo.bar''', license='''CC0''', features=Features({'''a''': Value('''int32''' )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train''', '''num_examples''': 42}], download_checksums={}, download_size=13_37, post_processing_size=4_42, dataset_size=12_34, size_in_bytes=13_37 + 4_42 + 12_34, ) _lowerCamelCase : Optional[Any] = dataset_info._to_yaml_dict() assert sorted(A_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) ) _lowerCamelCase : str = yaml.safe_dump(A_ ) _lowerCamelCase : Tuple = yaml.safe_load(A_ ) assert dataset_info_yaml_dict == reloaded def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : int = DatasetInfo() _lowerCamelCase : Dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''', [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=13_37 ), } ), ], ) def snake_case_ ( A_ : Optional[Any], A_ : DatasetInfosDict ): '''simple docstring''' _lowerCamelCase : List[str] = str(A_ ) dataset_infos_dict.write_to_directory(A_ ) _lowerCamelCase : List[Any] = DatasetInfosDict.from_directory(A_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _lowerCamelCase : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _lowerCamelCase : Any = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(A_, '''README.md''' ) )
83
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) class __snake_case ( _lowercase): snake_case__ : Tuple = "timm_backbone" def __init__( self : Union[str, Any] , __lowerCAmelCase : Any=None , __lowerCAmelCase : Optional[Any]=3 , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : List[str]=None , **__lowerCAmelCase : str , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = backbone _lowerCamelCase : Dict = num_channels _lowerCamelCase : Optional[int] = features_only _lowerCamelCase : List[Any] = use_pretrained_backbone _lowerCamelCase : int = True _lowerCamelCase : List[str] = out_indices if out_indices is not None else (-1,)
83
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __snake_case : def __init__( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : List[str]=2_4 , __lowerCAmelCase : str=1_6 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : int=4 , __lowerCAmelCase : int=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : List[Any]=0.02 , __lowerCAmelCase : str=None , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Union[str, Any]=2 , ): """simple docstring""" _lowerCamelCase : List[str] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : Tuple = patch_size _lowerCamelCase : Optional[int] = max_length _lowerCamelCase : List[Any] = num_mel_bins _lowerCamelCase : int = is_training _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : Dict = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : List[str] = scope _lowerCamelCase : Optional[int] = frequency_stride _lowerCamelCase : List[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowerCamelCase : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _lowerCamelCase : Union[str, Any] = (self.max_length - self.patch_size) // self.time_stride + 1 _lowerCamelCase : Any = frequency_out_dimension * time_out_dimension _lowerCamelCase : List[Any] = num_patches + 2 def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Optional[int] = self.get_config() return config, input_values, labels def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = ASTModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Optional[Any] = config_and_inputs _lowerCamelCase : int = {'''input_values''': input_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Any = False snake_case__ : List[Any] = False snake_case__ : Optional[Any] = False snake_case__ : Optional[Any] = False def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[int] = ASTModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCamelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : str = ['''input_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Union[str, Any] = ASTModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' ) _lowerCamelCase , _lowerCamelCase : str = torchaudio.load(A_ ) return audio, sampling_rate @require_torch @require_torchaudio class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.default_feature_extractor _lowerCamelCase : Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = self.default_feature_extractor _lowerCamelCase , _lowerCamelCase : List[Any] = prepare_audio() _lowerCamelCase : Dict = audio.squeeze().numpy() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , sampling_rate=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Tuple = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : Tuple = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
83
1
"""simple docstring""" import torch from transformers import AutoModel class __snake_case ( torch.nn.Module): def __init__( self : Any , __lowerCAmelCase : Any="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__lowerCAmelCase , self ).__init__() _lowerCamelCase : Union[str, Any] = AutoModel.from_pretrained(__lowerCAmelCase , return_dict=__lowerCAmelCase ) _lowerCamelCase : Tuple = torch.nn.CosineSimilarity(3 , 1E-08 ) _lowerCamelCase : str = torch.nn.Softmax(dim=1 ) def SCREAMING_SNAKE_CASE ( self : str , **__lowerCAmelCase : int ): """simple docstring""" return self.bert(**__lowerCAmelCase ).last_hidden_state def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=1 ): """simple docstring""" return self.softmax(T * self.cos(__lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Any = W_supports['''sizes'''].tolist() _lowerCamelCase : str = W_supports['''start_token_id'''].item() _lowerCamelCase : Optional[int] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] _lowerCamelCase : List[Any] = self.BERT(**__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = self.BERT(**__lowerCAmelCase ) _lowerCamelCase : List[Any] = None _lowerCamelCase : Tuple = None _lowerCamelCase : Optional[Any] = W_supports['''input_ids'''] == start_token_id _lowerCamelCase : Tuple = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__lowerCAmelCase ): if i == 0: _lowerCamelCase : List[str] = 0 else: _lowerCamelCase : Tuple = support_sizes[i - 1] _lowerCamelCase : List[Any] = S[s : s + size][start_token_masks[s : s + size]] _lowerCamelCase : Tuple = S[s : s + size][end_token_masks[s : s + size]] _lowerCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) _lowerCamelCase : List[Any] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: _lowerCamelCase : Optional[Any] = torch.vstack((p_starts, p_start) ) _lowerCamelCase : List[str] = torch.vstack((p_ends, p_end) ) else: _lowerCamelCase : List[Any] = p_start _lowerCamelCase : Optional[int] = p_end return p_starts, p_ends
83
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( A_ : Dict, A_ : bool = True, A_ : float = math.inf, A_ : float = -math.inf, A_ : float = math.inf, A_ : float = -math.inf, A_ : bool = False, A_ : float = 1_00, A_ : float = 0.01, A_ : float = 1, ): '''simple docstring''' _lowerCamelCase : Optional[int] = False _lowerCamelCase : str = search_prob _lowerCamelCase : str = start_temperate _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : int = 0 _lowerCamelCase : Any = None while not search_end: _lowerCamelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCamelCase : Tuple = current_state scores.append(A_ ) iterations += 1 _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCamelCase : List[Any] = random.randint(0, len(A_ ) - 1 ) # picking a random neighbor _lowerCamelCase : Dict = neighbors.pop(A_ ) _lowerCamelCase : Union[str, Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCamelCase : Optional[Any] = picked_neighbor else: _lowerCamelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCamelCase : Union[str, Any] = picked_neighbor _lowerCamelCase : List[str] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCamelCase : Tuple = True else: _lowerCamelCase : Optional[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A_ ), A_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def snake_case_ ( A_ : Optional[int], A_ : List[Any] ): '''simple docstring''' return (3 * x**2) - (6 * y) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
83
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "camembert" def __init__( self : Optional[Any] , __lowerCAmelCase : Any=3_0_5_2_2 , __lowerCAmelCase : List[str]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Optional[int]=5_1_2 , __lowerCAmelCase : str=2 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : List[Any]=1E-12 , __lowerCAmelCase : Union[str, Any]=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : str="absolute" , __lowerCAmelCase : Any=True , __lowerCAmelCase : Optional[int]=None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Optional[Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : List[str] = classifier_dropout class __snake_case ( _lowercase): @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
83
"""simple docstring""" from collections import namedtuple lowerCAmelCase__ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase__ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def snake_case_ ( A_ : float, A_ : str, A_ : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ''', '''.join(A_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ''', '''.join(A_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" class __snake_case : def __init__( self : List[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Dict = name _lowerCamelCase : Any = value _lowerCamelCase : Optional[Any] = weight def __repr__( self : Tuple ): """simple docstring""" return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.value def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.name def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.weight def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.value / self.weight def snake_case_ ( A_ : Optional[Any], A_ : str, A_ : str ): '''simple docstring''' _lowerCamelCase : int = [] for i in range(len(A_ ) ): menu.append(Things(name[i], value[i], weight[i] ) ) return menu def snake_case_ ( A_ : Dict, A_ : List[Any], A_ : Any ): '''simple docstring''' _lowerCamelCase : Optional[Any] = sorted(A_, key=A_, reverse=A_ ) _lowerCamelCase : Optional[int] = [] _lowerCamelCase , _lowerCamelCase : str = 0.0, 0.0 for i in range(len(A_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def snake_case_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case ( _lowercase): def __init__( self : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=9_9 , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : Optional[int]=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : int=5_1_2 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any="None" , __lowerCAmelCase : str=3 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[Any]=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Dict = use_input_mask _lowerCamelCase : Tuple = use_token_type_ids _lowerCamelCase : Optional[Any] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Optional[int] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : int = relative_attention _lowerCamelCase : Union[str, Any] = position_biased_input _lowerCamelCase : str = pos_att_type _lowerCamelCase : Tuple = scope def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : int = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : str = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : List[Any] = model(__lowerCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : Dict = DebertaVaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : Tuple = DebertaVaForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = DebertaVaForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : int = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True snake_case__ : List[Any] = False snake_case__ : int = False snake_case__ : Optional[Any] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) _lowerCamelCase : List[str] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] # compare the actual values for a slice. _lowerCamelCase : Union[str, Any] = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
83
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class __snake_case ( _lowercase): snake_case__ : Optional[int] = "dpt" def __init__( self : Optional[int] , __lowerCAmelCase : List[Any]=7_6_8 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : Tuple=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Optional[int]="gelu" , __lowerCAmelCase : Union[str, Any]=0.0 , __lowerCAmelCase : int=0.0 , __lowerCAmelCase : Any=0.02 , __lowerCAmelCase : Optional[Any]=1E-12 , __lowerCAmelCase : Dict=3_8_4 , __lowerCAmelCase : Any=1_6 , __lowerCAmelCase : Optional[int]=3 , __lowerCAmelCase : Tuple=False , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : int=[2, 5, 8, 1_1] , __lowerCAmelCase : Optional[Any]="project" , __lowerCAmelCase : Optional[Any]=[4, 2, 1, 0.5] , __lowerCAmelCase : Dict=[9_6, 1_9_2, 3_8_4, 7_6_8] , __lowerCAmelCase : str=2_5_6 , __lowerCAmelCase : Union[str, Any]=-1 , __lowerCAmelCase : Dict=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : List[str]=0.4 , __lowerCAmelCase : List[Any]=2_5_5 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Any=[1, 1_0_2_4, 2_4, 2_4] , __lowerCAmelCase : List[Any]=[0, 1] , __lowerCAmelCase : int=None , **__lowerCAmelCase : List[str] , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : str = hidden_size _lowerCamelCase : str = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('''Initializing the config with a `BiT` backbone.''' ) _lowerCamelCase : Any = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, } _lowerCamelCase : Any = BitConfig(**__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): logger.info('''Initializing the config with a `BiT` backbone.''' ) _lowerCamelCase : Tuple = BitConfig(**__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): _lowerCamelCase : str = backbone_config else: raise ValueError( f'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) _lowerCamelCase : List[Any] = backbone_featmap_shape _lowerCamelCase : str = neck_ignore_stages if readout_type != "project": raise ValueError('''Readout type must be \'project\' when using `DPT-hybrid` mode.''' ) else: _lowerCamelCase : Dict = None _lowerCamelCase : List[Any] = None _lowerCamelCase : List[Any] = [] _lowerCamelCase : str = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Optional[Any] = intermediate_size _lowerCamelCase : Any = hidden_act _lowerCamelCase : List[str] = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : str = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : int = image_size _lowerCamelCase : List[str] = patch_size _lowerCamelCase : List[Any] = num_channels _lowerCamelCase : Dict = qkv_bias _lowerCamelCase : Dict = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('''Readout_type must be one of [\'ignore\', \'add\', \'project\']''' ) _lowerCamelCase : List[Any] = readout_type _lowerCamelCase : Optional[int] = reassemble_factors _lowerCamelCase : Optional[int] = neck_hidden_sizes _lowerCamelCase : Optional[Any] = fusion_hidden_size _lowerCamelCase : Tuple = head_in_index _lowerCamelCase : Tuple = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) _lowerCamelCase : str = use_auxiliary_head _lowerCamelCase : Optional[int] = auxiliary_loss_weight _lowerCamelCase : List[str] = semantic_loss_ignore_index _lowerCamelCase : Dict = semantic_classifier_dropout def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : List[str] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: _lowerCamelCase : Any = self.backbone_config.to_dict() _lowerCamelCase : str = self.__class__.model_type return output
83
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = '''hf-internal-testing/tiny-random-bert''' lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''') lowerCAmelCase__ = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6''' class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = cached_file(__lowerCAmelCase , __lowerCAmelCase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__lowerCAmelCase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : Optional[int] = f.read() self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) self.assertTrue(os.path.isfile(__lowerCAmelCase ) ) # File is cached at the same place the second time. _lowerCamelCase : Tuple = cached_file(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Using a specific revision to test the full commit hash. _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''9b8c223''' ) self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): _lowerCamelCase : Optional[int] = cached_file('''tiny-random-bert''' , __lowerCAmelCase ) with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): _lowerCamelCase : str = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''aaaa''' ) with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : int = cached_file(__lowerCAmelCase , '''conf''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , '''conf''' ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : List[Any] = f.read() self.assertTrue(os.path.isfile(os.path.join(__lowerCAmelCase , '''.no_exist''' , __lowerCAmelCase , '''conf''' ) ) ) _lowerCamelCase : str = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = cached_file(__lowerCAmelCase , '''conf''' , local_files_only=__lowerCAmelCase , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Any = mock.Mock() _lowerCamelCase : Optional[Any] = 5_0_0 _lowerCamelCase : Dict = {} _lowerCamelCase : List[Any] = HTTPError _lowerCamelCase : int = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__lowerCAmelCase ) as mock_head: _lowerCamelCase : Union[str, Any] = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_connection_errors=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __lowerCAmelCase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase , revision='''ahaha''' ) _lowerCamelCase : Dict = get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase ) # The name is the cached name which is not very easy to test, so instead we load the content. _lowerCamelCase : Dict = json.loads(open(__lowerCAmelCase , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = Path(__lowerCAmelCase ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__lowerCAmelCase , '''a.txt''' ) , str(__lowerCAmelCase ) ) self.assertIsNone(get_file_from_repo(__lowerCAmelCase , '''b.txt''' ) )
83
1
"""simple docstring""" import comet # From: unbabel-comet import torch import datasets lowerCAmelCase__ = datasets.logging.get_logger(__name__) lowerCAmelCase__ = '''\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = "{COMET}: A Neural Framework for {MT} Evaluation", author = "Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon", booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)", month = nov, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.emnlp-main.213", pages = "2685--2702", } ''' lowerCAmelCase__ = '''\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. ''' lowerCAmelCase__ = ''' COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric(\'comet\') >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."] >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"] >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results["scores"]]) [0.19, 0.92] ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __snake_case ( datasets.Metric): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://unbabel.github.io/COMET/html/index.html''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''sources''': datasets.Value('''string''' , id='''sequence''' ), '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/Unbabel/COMET'''] , reference_urls=[ '''https://github.com/Unbabel/COMET''', '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''', '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''', ] , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Optional[int] ): """simple docstring""" if self.config_name == "default": _lowerCamelCase : Dict = comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da''' ) ) else: _lowerCamelCase : Optional[int] = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Any=None , __lowerCAmelCase : Optional[Any]=False ): """simple docstring""" if gpus is None: _lowerCamelCase : Any = 1 if torch.cuda.is_available() else 0 _lowerCamelCase : Optional[int] = {'''src''': sources, '''mt''': predictions, '''ref''': references} _lowerCamelCase : Optional[int] = [dict(zip(__lowerCAmelCase , __lowerCAmelCase ) ) for t in zip(*data.values() )] _lowerCamelCase , _lowerCamelCase : Dict = self.scorer.predict(__lowerCAmelCase , gpus=__lowerCAmelCase , progress_bar=__lowerCAmelCase ) return {"mean_score": mean_score, "scores": scores}
83
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( _lowercase): snake_case__ : List[str] = "cvt" def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=3 , __lowerCAmelCase : List[str]=[7, 3, 3] , __lowerCAmelCase : int=[4, 2, 2] , __lowerCAmelCase : int=[2, 1, 1] , __lowerCAmelCase : str=[6_4, 1_9_2, 3_8_4] , __lowerCAmelCase : Dict=[1, 3, 6] , __lowerCAmelCase : Optional[Any]=[1, 2, 1_0] , __lowerCAmelCase : Dict=[4.0, 4.0, 4.0] , __lowerCAmelCase : Dict=[0.0, 0.0, 0.0] , __lowerCAmelCase : Union[str, Any]=[0.0, 0.0, 0.0] , __lowerCAmelCase : int=[0.0, 0.0, 0.1] , __lowerCAmelCase : Union[str, Any]=[True, True, True] , __lowerCAmelCase : str=[False, False, True] , __lowerCAmelCase : List[str]=["dw_bn", "dw_bn", "dw_bn"] , __lowerCAmelCase : List[Any]=[3, 3, 3] , __lowerCAmelCase : Dict=[1, 1, 1] , __lowerCAmelCase : str=[2, 2, 2] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Any=1E-12 , **__lowerCAmelCase : int , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : int = patch_sizes _lowerCamelCase : Optional[Any] = patch_stride _lowerCamelCase : str = patch_padding _lowerCamelCase : Any = embed_dim _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Dict = depth _lowerCamelCase : Optional[int] = mlp_ratio _lowerCamelCase : Any = attention_drop_rate _lowerCamelCase : Any = drop_rate _lowerCamelCase : Dict = drop_path_rate _lowerCamelCase : Optional[int] = qkv_bias _lowerCamelCase : int = cls_token _lowerCamelCase : int = qkv_projection_method _lowerCamelCase : Optional[Any] = kernel_qkv _lowerCamelCase : List[str] = padding_kv _lowerCamelCase : Tuple = stride_kv _lowerCamelCase : Union[str, Any] = padding_q _lowerCamelCase : Optional[Any] = stride_q _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps
83
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __snake_case : def __init__( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : List[str]=2_4 , __lowerCAmelCase : str=1_6 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : int=4 , __lowerCAmelCase : int=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : List[Any]=0.02 , __lowerCAmelCase : str=None , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Union[str, Any]=2 , ): """simple docstring""" _lowerCamelCase : List[str] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : Tuple = patch_size _lowerCamelCase : Optional[int] = max_length _lowerCamelCase : List[Any] = num_mel_bins _lowerCamelCase : int = is_training _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : Dict = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : List[str] = scope _lowerCamelCase : Optional[int] = frequency_stride _lowerCamelCase : List[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowerCamelCase : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _lowerCamelCase : Union[str, Any] = (self.max_length - self.patch_size) // self.time_stride + 1 _lowerCamelCase : Any = frequency_out_dimension * time_out_dimension _lowerCamelCase : List[Any] = num_patches + 2 def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Optional[int] = self.get_config() return config, input_values, labels def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = ASTModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Optional[Any] = config_and_inputs _lowerCamelCase : int = {'''input_values''': input_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Any = False snake_case__ : List[Any] = False snake_case__ : Optional[Any] = False snake_case__ : Optional[Any] = False def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[int] = ASTModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCamelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : str = ['''input_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Union[str, Any] = ASTModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' ) _lowerCamelCase , _lowerCamelCase : str = torchaudio.load(A_ ) return audio, sampling_rate @require_torch @require_torchaudio class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.default_feature_extractor _lowerCamelCase : Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = self.default_feature_extractor _lowerCamelCase , _lowerCamelCase : List[Any] = prepare_audio() _lowerCamelCase : Dict = audio.squeeze().numpy() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , sampling_rate=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Tuple = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : Tuple = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
83
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __snake_case ( _lowercase): snake_case__ : torch.FloatTensor snake_case__ : torch.FloatTensor class __snake_case ( _lowercase , _lowercase): snake_case__ : int = 1 @register_to_config def __init__( self : str , __lowerCAmelCase : int = 2_0_0_0 , __lowerCAmelCase : float = 0.15 , __lowerCAmelCase : float = 0.01 , __lowerCAmelCase : float = 13_48.0 , __lowerCAmelCase : float = 1E-5 , __lowerCAmelCase : int = 1 , ): """simple docstring""" _lowerCamelCase : Optional[int] = sigma_max # setable values _lowerCamelCase : Dict = None self.set_sigmas(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : Union[str, torch.device] = None ): """simple docstring""" _lowerCamelCase : Tuple = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCamelCase : Optional[int] = torch.linspace(1 , __lowerCAmelCase , __lowerCAmelCase , device=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None ): """simple docstring""" _lowerCamelCase : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCamelCase : int = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCamelCase : Optional[int] = torch.exp(torch.linspace(math.log(__lowerCAmelCase ) , math.log(__lowerCAmelCase ) , __lowerCAmelCase ) ) _lowerCamelCase : Tuple = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : int , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) _lowerCamelCase : Tuple = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCamelCase : Dict = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCamelCase : Optional[int] = timesteps.to(self.discrete_sigmas.device ) _lowerCamelCase : Any = self.discrete_sigmas[timesteps].to(sample.device ) _lowerCamelCase : int = self.get_adjacent_sigma(__lowerCAmelCase , __lowerCAmelCase ).to(sample.device ) _lowerCamelCase : Any = torch.zeros_like(__lowerCAmelCase ) _lowerCamelCase : Any = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCamelCase : Union[str, Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): _lowerCamelCase : List[Any] = diffusion.unsqueeze(-1 ) _lowerCamelCase : int = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCamelCase : List[str] = randn_tensor( sample.shape , layout=sample.layout , generator=__lowerCAmelCase , device=sample.device , dtype=sample.dtype ) _lowerCamelCase : List[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCamelCase : int = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=__lowerCAmelCase , prev_sample_mean=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCamelCase : Union[str, Any] = randn_tensor(sample.shape , layout=sample.layout , generator=__lowerCAmelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr _lowerCamelCase : Union[str, Any] = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : str = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCamelCase : Tuple = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): _lowerCamelCase : str = step_size.unsqueeze(-1 ) _lowerCamelCase : Any = sample + step_size * model_output _lowerCamelCase : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , ): """simple docstring""" _lowerCamelCase : Dict = timesteps.to(original_samples.device ) _lowerCamelCase : Union[str, Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] _lowerCamelCase : Union[str, Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(__lowerCAmelCase ) * sigmas[:, None, None, None] ) _lowerCamelCase : int = noise + original_samples return noisy_samples def __len__( self : Optional[int] ): """simple docstring""" return self.config.num_train_timesteps
83
1
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def snake_case_ ( A_ : List[Any], A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Optional[int] = UniSpeechSatForSequenceClassification.from_pretrained(A_, config=A_ ) _lowerCamelCase : List[str] = downstream_dict['''projector.weight'''] _lowerCamelCase : Union[str, Any] = downstream_dict['''projector.bias'''] _lowerCamelCase : Union[str, Any] = downstream_dict['''model.post_net.linear.weight'''] _lowerCamelCase : int = downstream_dict['''model.post_net.linear.bias'''] return model def snake_case_ ( A_ : List[str], A_ : Optional[Any], A_ : Dict ): '''simple docstring''' _lowerCamelCase : int = UniSpeechSatForAudioFrameClassification.from_pretrained(A_, config=A_ ) _lowerCamelCase : Dict = downstream_dict['''model.linear.weight'''] _lowerCamelCase : int = downstream_dict['''model.linear.bias'''] return model def snake_case_ ( A_ : int, A_ : str, A_ : Tuple ): '''simple docstring''' _lowerCamelCase : List[Any] = UniSpeechSatForXVector.from_pretrained(A_, config=A_ ) _lowerCamelCase : Tuple = downstream_dict['''connector.weight'''] _lowerCamelCase : Any = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): _lowerCamelCase : Dict = downstream_dict[ F'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] _lowerCamelCase : int = downstream_dict[F'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] _lowerCamelCase : str = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] _lowerCamelCase : Optional[Any] = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] _lowerCamelCase : List[str] = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] _lowerCamelCase : int = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] _lowerCamelCase : Dict = downstream_dict['''objective.W'''] return model @torch.no_grad() def snake_case_ ( A_ : Union[str, Any], A_ : Optional[int], A_ : Union[str, Any], A_ : str ): '''simple docstring''' _lowerCamelCase : Optional[Any] = torch.load(A_, map_location='''cpu''' ) _lowerCamelCase : str = checkpoint['''Downstream'''] _lowerCamelCase : Any = UniSpeechSatConfig.from_pretrained(A_ ) _lowerCamelCase : Tuple = WavaVecaFeatureExtractor.from_pretrained( A_, return_attention_mask=A_, do_normalize=A_ ) _lowerCamelCase : Tuple = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): _lowerCamelCase : Union[str, Any] = convert_classification(A_, A_, A_ ) elif arch.endswith('''ForAudioFrameClassification''' ): _lowerCamelCase : int = convert_diarization(A_, A_, A_ ) elif arch.endswith('''ForXVector''' ): _lowerCamelCase : Tuple = convert_xvector(A_, A_, A_ ) else: raise NotImplementedError(F'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: _lowerCamelCase : Tuple = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(A_ ) hf_model.save_pretrained(A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') lowerCAmelCase__ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
83
"""simple docstring""" from torch import nn def snake_case_ ( A_ : int ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'''Unsupported activation function: {act_fn}''' )
83
1
"""simple docstring""" from importlib import import_module from .logging import get_logger lowerCAmelCase__ = get_logger(__name__) class __snake_case : def __init__( self : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ): """simple docstring""" _lowerCamelCase : List[str] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) _lowerCamelCase : List[str] = module._original_module if isinstance(__lowerCAmelCase , _PatchedModuleObj ) else module class __snake_case : snake_case__ : Optional[Any] = [] def __init__( self : str , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int]=None ): """simple docstring""" _lowerCamelCase : Union[str, Any] = obj _lowerCamelCase : Tuple = target _lowerCamelCase : Optional[Any] = new _lowerCamelCase : Optional[Any] = target.split('''.''' )[0] _lowerCamelCase : List[str] = {} _lowerCamelCase : Optional[Any] = attrs or [] def __enter__( self : Optional[Any] ): """simple docstring""" *_lowerCamelCase , _lowerCamelCase : str = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__lowerCAmelCase ) ): try: _lowerCamelCase : Tuple = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): _lowerCamelCase : Optional[int] = getattr(self.obj , __lowerCAmelCase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__lowerCAmelCase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): _lowerCamelCase : Optional[Any] = obj_attr # patch at top level setattr(self.obj , __lowerCAmelCase , _PatchedModuleObj(__lowerCAmelCase , attrs=self.attrs ) ) _lowerCamelCase : Tuple = getattr(self.obj , __lowerCAmelCase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__lowerCAmelCase , __lowerCAmelCase , _PatchedModuleObj(getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) , attrs=self.attrs ) ) _lowerCamelCase : List[Any] = getattr(__lowerCAmelCase , __lowerCAmelCase ) # finally set the target attribute setattr(__lowerCAmelCase , __lowerCAmelCase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: _lowerCamelCase : List[str] = getattr(import_module('''.'''.join(__lowerCAmelCase ) ) , __lowerCAmelCase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __lowerCAmelCase ) is attr_value: _lowerCamelCase : Dict = getattr(self.obj , __lowerCAmelCase ) setattr(self.obj , __lowerCAmelCase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" _lowerCamelCase : str = globals()['''__builtins__'''][target_attr] setattr(self.obj , __lowerCAmelCase , self.new ) else: raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self : Optional[int] , *__lowerCAmelCase : Dict ): """simple docstring""" for attr in list(self.original ): setattr(self.obj , __lowerCAmelCase , self.original.pop(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" self.__enter__() self._active_patches.append(self ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
83
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def snake_case_ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(F'''| 0 | 0 | {nor_gate(0, 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0, 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1, 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1, 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
83
1
"""simple docstring""" import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device 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, assert_mean_pixel_difference, ) enable_full_determinism() class __snake_case ( _lowercase , _lowercase , _lowercase , unittest.TestCase): snake_case__ : str = StableUnCLIPPipeline snake_case__ : Optional[int] = TEXT_TO_IMAGE_PARAMS snake_case__ : int = TEXT_TO_IMAGE_BATCH_PARAMS snake_case__ : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS snake_case__ : Optional[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false snake_case__ : Dict = False def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : int = 3_2 _lowerCamelCase : Any = embedder_hidden_size # prior components torch.manual_seed(0 ) _lowerCamelCase : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) _lowerCamelCase : List[Any] = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__lowerCAmelCase , projection_dim=__lowerCAmelCase , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) _lowerCamelCase : Dict = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=__lowerCAmelCase , num_layers=1 , ) torch.manual_seed(0 ) _lowerCamelCase : Optional[int] = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_0_0_0 , clip_sample=__lowerCAmelCase , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) _lowerCamelCase : int = StableUnCLIPImageNormalizer(embedding_dim=__lowerCAmelCase ) _lowerCamelCase : List[str] = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) _lowerCamelCase : Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) _lowerCamelCase : Optional[Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__lowerCAmelCase , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) _lowerCamelCase : str = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__lowerCAmelCase , layers_per_block=1 , upcast_attention=__lowerCAmelCase , use_linear_projection=__lowerCAmelCase , ) torch.manual_seed(0 ) _lowerCamelCase : Optional[Any] = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type='''v_prediction''' , set_alpha_to_one=__lowerCAmelCase , steps_offset=1 , ) torch.manual_seed(0 ) _lowerCamelCase : Optional[Any] = AutoencoderKL() _lowerCamelCase : Dict = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int]=0 ): """simple docstring""" if str(__lowerCAmelCase ).startswith('''mps''' ): _lowerCamelCase : List[Any] = torch.manual_seed(__lowerCAmelCase ) else: _lowerCamelCase : str = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) _lowerCamelCase : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Tuple = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=__lowerCAmelCase ) @slow @require_torch_gpu class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) _lowerCamelCase : Optional[Any] = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowerCamelCase : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) _lowerCamelCase : Tuple = pipe('''anime turle''' , generator=__lowerCAmelCase , output_type='''np''' ) _lowerCamelCase : Dict = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCamelCase : Union[str, Any] = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) _lowerCamelCase : Any = pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowerCamelCase : List[str] = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) _lowerCamelCase : Dict = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
83
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : list[list[int]] ): '''simple docstring''' for i in range(1, len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(A_ ) ): for j in range(1, len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" def snake_case_ ( A_ : str, A_ : str ): '''simple docstring''' _lowerCamelCase : int = len(A_ ) _lowerCamelCase : int = len(A_ ) _lowerCamelCase : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) _lowerCamelCase : list = [] for char_count in range(A_ ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(A_ ) if __name__ == "__main__": print(alternative_string_arrange('''AB''', '''XYZ'''), end=''' ''')
83
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Optional[int] = data _lowerCamelCase : Node[T] | None = None def __str__( self : Optional[Any] ): """simple docstring""" return f'''{self.data}''' class __snake_case ( Generic[T]): def __init__( self : int ): """simple docstring""" _lowerCamelCase : Node[T] | None = None def __iter__( self : str ): """simple docstring""" _lowerCamelCase : List[str] = self.top while node: yield node.data _lowerCamelCase : Any = node.next def __str__( self : int ): """simple docstring""" return "->".join([str(__lowerCAmelCase ) for item in self] ) def __len__( self : int ): """simple docstring""" return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.top is None def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Tuple = Node(__lowerCAmelCase ) if not self.is_empty(): _lowerCamelCase : Optional[int] = self.top _lowerCamelCase : List[str] = node def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , __lowerCAmelCase ) _lowerCamelCase : Any = self.top _lowerCamelCase : Any = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = None if __name__ == "__main__": from doctest import testmod testmod()
83
1
"""simple docstring""" from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class __snake_case ( _lowercase): def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = SMALL_MODEL_IDENTIFIER _lowerCamelCase : Union[str, Any] = '''pt''' _lowerCamelCase : Optional[int] = '''tf''' def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Any = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : Tuple = TFAutoModel.from_pretrained(self.test_model , from_pt=__lowerCAmelCase ) model_tf.save_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Dict = '''mock_framework''' # Framework provided - return whatever the user provides _lowerCamelCase : str = FeaturesManager.determine_framework(self.test_model , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowerCAmelCase ) _lowerCamelCase : List[Any] = FeaturesManager.determine_framework(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowerCAmelCase ) _lowerCamelCase : int = FeaturesManager.determine_framework(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowerCAmelCase ) _lowerCamelCase : List[Any] = FeaturesManager.determine_framework(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = FeaturesManager.determine_framework(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Optional[Any] = FeaturesManager.determine_framework(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : List[str] = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCAmelCase ): _lowerCamelCase : Optional[int] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow _lowerCamelCase : List[str] = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __lowerCAmelCase ): _lowerCamelCase : Optional[int] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch _lowerCamelCase : Optional[int] = MagicMock(return_value=__lowerCAmelCase ) _lowerCamelCase : Dict = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __lowerCAmelCase ): _lowerCamelCase : Any = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCAmelCase , self.framework_pt ) # Both not in environment -> raise error _lowerCamelCase : Union[str, Any] = MagicMock(return_value=__lowerCAmelCase ) _lowerCamelCase : Tuple = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __lowerCAmelCase ): with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Any = FeaturesManager.determine_framework(self.test_model )
83
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase__ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCAmelCase__ = spec.loader.load_module() lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCAmelCase__ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = [] for config_class in list(CONFIG_MAPPING.values() ): _lowerCamelCase : Tuple = False # source code of `config_class` _lowerCamelCase : int = inspect.getsource(A_ ) _lowerCamelCase : str = _re_checkpoint.findall(A_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` _lowerCamelCase , _lowerCamelCase : Tuple = checkpoint # verify the checkpoint name corresponds to the checkpoint link _lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _lowerCamelCase : Union[str, Any] = True break _lowerCamelCase : Tuple = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class __snake_case ( unittest.TestCase): pass @nightly @require_torch_gpu class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : int = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : str = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Dict = torch.manual_seed(0 ) _lowerCamelCase : List[Any] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : int = generator.manual_seed(0 ) _lowerCamelCase : List[str] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Optional[int] = torch.manual_seed(0 ) _lowerCamelCase : int = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images _lowerCamelCase : List[str] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Dict = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
83
1
"""simple docstring""" import os from typing import Dict, List, Tuple, TypeVar, Union lowerCAmelCase__ = TypeVar('''T''') lowerCAmelCase__ = Union[List[T], Tuple[T, ...]] lowerCAmelCase__ = Union[T, List[T], Dict[str, T]] lowerCAmelCase__ = Union[str, bytes, os.PathLike]
83
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = '''1''' lowerCAmelCase__ = '''0''' lowerCAmelCase__ = '''1''' lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('''Create inference session...''') lowerCAmelCase__ = ['''TensorrtExecutionProvider''', '''CUDAExecutionProvider'''] lowerCAmelCase__ = ort.InferenceSession('''model.onnx''', sess_options=sess_opt, providers=execution_provider) lowerCAmelCase__ = ort.RunOptions() lowerCAmelCase__ = 128 lowerCAmelCase__ = 1 lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) print('''Warm up phase...''') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Start inference...''') lowerCAmelCase__ = time.time() lowerCAmelCase__ = 2000 lowerCAmelCase__ = {} for iter in range(max_iters): lowerCAmelCase__ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Average Inference Time = {:.3f} ms'''.format((time.time() - start_time) * 1000 / max_iters))
83
1
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : Tuple = AutoencoderKL snake_case__ : Optional[int] = "sample" snake_case__ : Optional[Any] = 1e-2 @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = 4 _lowerCamelCase : Optional[Any] = 3 _lowerCamelCase : List[str] = (3_2, 3_2) _lowerCamelCase : Any = floats_tensor((batch_size, num_channels) + sizes ).to(__lowerCAmelCase ) return {"sample": image} @property def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return (3, 3_2, 3_2) @property def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return (3, 3_2, 3_2) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = { '''block_out_channels''': [3_2, 6_4], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } _lowerCamelCase : Tuple = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass @unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.prepare_init_args_and_inputs_for_common() _lowerCamelCase : List[str] = self.model_class(**__lowerCAmelCase ) model.to(__lowerCAmelCase ) assert not model.is_gradient_checkpointing and model.training _lowerCamelCase : Union[str, Any] = model(**__lowerCAmelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() _lowerCamelCase : List[Any] = torch.randn_like(__lowerCAmelCase ) _lowerCamelCase : Tuple = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing _lowerCamelCase : List[Any] = self.model_class(**__lowerCAmelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__lowerCAmelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training _lowerCamelCase : List[Any] = model_a(**__lowerCAmelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() _lowerCamelCase : Any = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) _lowerCamelCase : Optional[int] = dict(model.named_parameters() ) _lowerCamelCase : Any = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : List[Any] = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' ) _lowerCamelCase : int = model.to(__lowerCAmelCase ) model.eval() if torch_device == "mps": _lowerCamelCase : int = torch.manual_seed(0 ) else: _lowerCamelCase : str = torch.Generator(device=__lowerCAmelCase ).manual_seed(0 ) _lowerCamelCase : int = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) _lowerCamelCase : Optional[int] = image.to(__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : str = model(__lowerCAmelCase , sample_posterior=__lowerCAmelCase , generator=__lowerCAmelCase ).sample _lowerCamelCase : List[str] = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": _lowerCamelCase : str = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": _lowerCamelCase : Optional[int] = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: _lowerCamelCase : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__lowerCAmelCase , __lowerCAmelCase , rtol=1E-2 ) ) @slow class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any ): """simple docstring""" return f'''gaussian_noise_s={seed}_shape={"_".join([str(__lowerCAmelCase ) for s in shape] )}.npy''' def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict=0 , __lowerCAmelCase : Tuple=(4, 3, 5_1_2, 5_1_2) , __lowerCAmelCase : Tuple=False ): """simple docstring""" _lowerCamelCase : str = torch.floataa if fpaa else torch.floataa _lowerCamelCase : List[Any] = torch.from_numpy(load_hf_numpy(self.get_file_format(__lowerCAmelCase , __lowerCAmelCase ) ) ).to(__lowerCAmelCase ).to(__lowerCAmelCase ) return image def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : List[str]="CompVis/stable-diffusion-v1-4" , __lowerCAmelCase : List[str]=False ): """simple docstring""" _lowerCamelCase : Any = '''fp16''' if fpaa else None _lowerCamelCase : str = torch.floataa if fpaa else torch.floataa _lowerCamelCase : Any = AutoencoderKL.from_pretrained( __lowerCAmelCase , subfolder='''vae''' , torch_dtype=__lowerCAmelCase , revision=__lowerCAmelCase , ) model.to(__lowerCAmelCase ).eval() return model def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : int=0 ): """simple docstring""" if torch_device == "mps": return torch.manual_seed(__lowerCAmelCase ) return torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) @parameterized.expand( [ # fmt: off [3_3, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [4_7, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Dict = self.get_sd_vae_model() _lowerCamelCase : List[str] = self.get_sd_image(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = self.get_generator(__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : Any = model(__lowerCAmelCase , generator=__lowerCAmelCase , sample_posterior=__lowerCAmelCase ).sample assert sample.shape == image.shape _lowerCamelCase : Optional[int] = sample[-1, -2:, -2:, :2].flatten().float().cpu() _lowerCamelCase : Tuple = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [4_7, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = self.get_sd_vae_model(fpaa=__lowerCAmelCase ) _lowerCamelCase : int = self.get_sd_image(__lowerCAmelCase , fpaa=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = self.get_generator(__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : Optional[Any] = model(__lowerCAmelCase , generator=__lowerCAmelCase , sample_posterior=__lowerCAmelCase ).sample assert sample.shape == image.shape _lowerCamelCase : Union[str, Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() _lowerCamelCase : Optional[Any] = torch.tensor(__lowerCAmelCase ) assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [4_7, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.get_sd_vae_model() _lowerCamelCase : int = self.get_sd_image(__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : List[str] = model(__lowerCAmelCase ).sample assert sample.shape == image.shape _lowerCamelCase : Optional[int] = sample[-1, -2:, -2:, :2].flatten().float().cpu() _lowerCamelCase : Tuple = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [3_7, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : Dict = self.get_sd_vae_model() _lowerCamelCase : Any = self.get_sd_image(__lowerCAmelCase , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): _lowerCamelCase : List[Any] = model.decode(__lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] _lowerCamelCase : Tuple = sample[-1, -2:, :2, -2:].flatten().cpu() _lowerCamelCase : List[Any] = torch.tensor(__lowerCAmelCase ) assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [1_6, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : str = self.get_sd_vae_model(fpaa=__lowerCAmelCase ) _lowerCamelCase : int = self.get_sd_image(__lowerCAmelCase , shape=(3, 4, 6_4, 6_4) , fpaa=__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : Dict = model.decode(__lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] _lowerCamelCase : Dict = sample[-1, -2:, :2, -2:].flatten().float().cpu() _lowerCamelCase : Union[str, Any] = torch.tensor(__lowerCAmelCase ) assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = self.get_sd_vae_model(fpaa=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = self.get_sd_image(__lowerCAmelCase , shape=(3, 4, 6_4, 6_4) , fpaa=__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : List[str] = model.decode(__lowerCAmelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): _lowerCamelCase : Optional[int] = model.decode(__lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Dict = self.get_sd_vae_model() _lowerCamelCase : List[str] = self.get_sd_image(__lowerCAmelCase , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): _lowerCamelCase : Optional[int] = model.decode(__lowerCAmelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): _lowerCamelCase : Any = model.decode(__lowerCAmelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [4_7, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.get_sd_vae_model() _lowerCamelCase : Optional[Any] = self.get_sd_image(__lowerCAmelCase ) _lowerCamelCase : List[str] = self.get_generator(__lowerCAmelCase ) with torch.no_grad(): _lowerCamelCase : Tuple = model.encode(__lowerCAmelCase ).latent_dist _lowerCamelCase : Tuple = dist.sample(generator=__lowerCAmelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] _lowerCamelCase : Optional[Any] = sample[0, -1, -3:, -3:].flatten().cpu() _lowerCamelCase : str = torch.tensor(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = 3E-3 if torch_device != '''mps''' else 1E-2 assert torch_all_close(__lowerCAmelCase , __lowerCAmelCase , atol=__lowerCAmelCase )
83
"""simple docstring""" import colorsys from PIL import Image # type: ignore def snake_case_ ( A_ : float, A_ : float, A_ : int ): '''simple docstring''' _lowerCamelCase : List[Any] = x _lowerCamelCase : List[Any] = y for step in range(A_ ): # noqa: B007 _lowerCamelCase : Dict = a * a - b * b + x _lowerCamelCase : List[str] = 2 * a * b + y _lowerCamelCase : Any = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(A_, 1, 1 ) ) def snake_case_ ( A_ : int = 8_00, A_ : int = 6_00, A_ : float = -0.6, A_ : float = 0, A_ : float = 3.2, A_ : int = 50, A_ : bool = True, ): '''simple docstring''' _lowerCamelCase : Tuple = Image.new('''RGB''', (image_width, image_height) ) _lowerCamelCase : int = img.load() # loop through the image-coordinates for image_x in range(A_ ): for image_y in range(A_ ): # determine the figure-coordinates based on the image-coordinates _lowerCamelCase : Optional[Any] = figure_width / image_width * image_height _lowerCamelCase : List[Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width _lowerCamelCase : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height _lowerCamelCase : str = get_distance(A_, A_, A_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: _lowerCamelCase : Dict = get_color_coded_rgb(A_ ) else: _lowerCamelCase : str = get_black_and_white_rgb(A_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCAmelCase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
83
1
"""simple docstring""" import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin 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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case : def __init__( self : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : int=3_2 , __lowerCAmelCase : int=3 , __lowerCAmelCase : Union[str, Any]=4 , __lowerCAmelCase : Union[str, Any]=[1_0, 2_0, 3_0, 4_0] , __lowerCAmelCase : List[str]=[2, 2, 3, 2] , __lowerCAmelCase : int=True , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : Optional[Any]=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : List[Any]=["stage2", "stage3", "stage4"] , __lowerCAmelCase : Union[str, Any]=[2, 3, 4] , __lowerCAmelCase : int=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : Optional[int] = image_size _lowerCamelCase : Union[str, Any] = num_channels _lowerCamelCase : List[str] = num_stages _lowerCamelCase : Union[str, Any] = hidden_sizes _lowerCamelCase : int = depths _lowerCamelCase : str = is_training _lowerCamelCase : Dict = use_labels _lowerCamelCase : Union[str, Any] = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = num_labels _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : int = out_features _lowerCamelCase : str = out_indices _lowerCamelCase : str = scope def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCamelCase : Optional[int] = None if self.use_labels: _lowerCamelCase : Any = ids_tensor([self.batch_size] , self.num_labels ) _lowerCamelCase : Dict = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Dict = ConvNextModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ) # 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 // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ConvNextForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ConvNextBackbone(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _lowerCamelCase : int = None _lowerCamelCase : Optional[int] = ConvNextBackbone(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[int] = config_and_inputs _lowerCamelCase : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : Dict = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) snake_case__ : Dict = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) snake_case__ : Optional[int] = True snake_case__ : Optional[int] = False snake_case__ : Optional[int] = False snake_case__ : Union[str, Any] = False snake_case__ : Tuple = False def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = ConvNextModelTester(self ) _lowerCamelCase : Tuple = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return @unittest.skip(reason='''ConvNext does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" pass @unittest.skip(reason='''ConvNext does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass @unittest.skip(reason='''ConvNext does not use feedforward chunking''' ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : List[str] = model_class(__lowerCAmelCase ) _lowerCamelCase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : int = [*signature.parameters.keys()] _lowerCamelCase : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" def check_hidden_states_output(__lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict ): _lowerCamelCase : List[str] = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): _lowerCamelCase : Tuple = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) _lowerCamelCase : int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCamelCase : Tuple = self.model_tester.num_stages self.assertEqual(len(__lowerCAmelCase ) , expected_num_stages + 1 ) # ConvNext'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 // 4, self.model_tester.image_size // 4] , ) _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase : Union[str, Any] = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = ConvNextModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Dict = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Dict = ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''' ).to(__lowerCAmelCase ) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Union[str, Any] = prepare_img() _lowerCamelCase : Tuple = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Dict = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : str = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : int = torch.tensor([-0.02_60, -0.47_39, 0.19_11] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) ) @require_torch class __snake_case ( unittest.TestCase , _lowercase): snake_case__ : Any = (ConvNextBackbone,) if is_torch_available() else () snake_case__ : Union[str, Any] = ConvNextConfig snake_case__ : int = False def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ConvNextModelTester(self )
83
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ): '''simple docstring''' _lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {} _lowerCamelCase : Union[str, Any] = padding_side return tokenizer( [line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, ) def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ): '''simple docstring''' _lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ): """simple docstring""" super().__init__() _lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' ) _lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' ) _lowerCamelCase : List[Any] = self.get_char_lens(self.src_file ) _lowerCamelCase : Optional[int] = max_source_length _lowerCamelCase : Optional[Any] = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _lowerCamelCase : List[Any] = tokenizer _lowerCamelCase : List[Any] = prefix if n_obs is not None: _lowerCamelCase : List[str] = self.src_lens[:n_obs] _lowerCamelCase : int = src_lang _lowerCamelCase : Union[str, Any] = tgt_lang def __len__( self : int ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = index + 1 # linecache starts at 1 _lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' ) _lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowerCAmelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _lowerCamelCase : Optional[int] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer ) _lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' ) _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' ) _lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze() _lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() _lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ): """simple docstring""" return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) _lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowerCAmelCase__ = getLogger(__name__) def snake_case_ ( A_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(A_ ) ) def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Dict = get_git_info() save_json(A_, os.path.join(A_, '''git_log.json''' ) ) def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ): '''simple docstring''' with open(A_, '''w''' ) as f: json.dump(A_, A_, indent=A_, **A_ ) def snake_case_ ( A_ : Any ): '''simple docstring''' with open(A_ ) as f: return json.load(A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ ) _lowerCamelCase : str = { '''repo_id''': str(A_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case_ ( A_ : Callable, A_ : Iterable ): '''simple docstring''' return list(map(A_, A_ ) ) def snake_case_ ( A_ : str, A_ : Tuple ): '''simple docstring''' with open(A_, '''wb''' ) as f: return pickle.dump(A_, A_ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' def remove_articles(A_ : str ): return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ ) def white_space_fix(A_ : Any ): return " ".join(text.split() ) def remove_punc(A_ : List[Any] ): _lowerCamelCase : Any = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case_ ( A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : str = normalize_answer(A_ ).split() _lowerCamelCase : int = normalize_answer(A_ ).split() _lowerCamelCase : str = Counter(A_ ) & Counter(A_ ) _lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 _lowerCamelCase : int = 1.0 * num_same / len(A_ ) _lowerCamelCase : str = 1.0 * num_same / len(A_ ) _lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case_ ( A_ : Dict, A_ : str ): '''simple docstring''' return normalize_answer(A_ ) == normalize_answer(A_ ) def snake_case_ ( A_ : List[str], A_ : List[str] ): '''simple docstring''' assert len(A_ ) == len(A_ ) _lowerCamelCase : Optional[Any] = 0 for hypo, pred in zip(A_, A_ ): em += exact_match_score(A_, A_ ) if len(A_ ) > 0: em /= len(A_ ) return {"em": em} def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Dict = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _lowerCamelCase : Tuple = '''dropout_rate''' for p in extra_params: if getattr(A_, A_, A_ ): if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) ) delattr(A_, A_ ) continue _lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p] setattr(A_, A_, getattr(A_, A_ ) ) delattr(A_, A_ ) return hparams, config
83
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : int = ArgumentParser('''Accelerate CLI tool''', usage='''accelerate <command> [<args>]''', allow_abbrev=A_ ) _lowerCamelCase : Union[str, Any] = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=A_ ) env_command_parser(subparsers=A_ ) launch_command_parser(subparsers=A_ ) tpu_command_parser(subparsers=A_ ) test_command_parser(subparsers=A_ ) # Let's go _lowerCamelCase : str = parser.parse_args() if not hasattr(A_, '''func''' ): parser.print_help() exit(1 ) # Run args.func(A_ ) if __name__ == "__main__": main()
83
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "camembert" def __init__( self : Optional[Any] , __lowerCAmelCase : Any=3_0_5_2_2 , __lowerCAmelCase : List[str]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Optional[int]=5_1_2 , __lowerCAmelCase : str=2 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : List[Any]=1E-12 , __lowerCAmelCase : Union[str, Any]=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : str="absolute" , __lowerCAmelCase : Any=True , __lowerCAmelCase : Optional[int]=None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Optional[Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : List[str] = classifier_dropout class __snake_case ( _lowercase): @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
83
1
"""simple docstring""" import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever lowerCAmelCase__ = logging.getLogger(__name__) class __snake_case ( _lowercase): def __init__( self : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Any , __lowerCAmelCase : List[str]=None ): """simple docstring""" super().__init__( __lowerCAmelCase , question_encoder_tokenizer=__lowerCAmelCase , generator_tokenizer=__lowerCAmelCase , index=__lowerCAmelCase , init_retrieval=__lowerCAmelCase , ) _lowerCamelCase : List[str] = None def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : int ): """simple docstring""" logger.info('''initializing retrieval''' ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info('''dist initialized''' ) # needs to be set manually _lowerCamelCase : str = self._infer_socket_ifname() # avoid clash with the NCCL port _lowerCamelCase : Optional[int] = str(distributed_port + 1 ) _lowerCamelCase : Dict = dist.new_group(ranks=__lowerCAmelCase , backend='''gloo''' ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info('''dist not initialized / main''' ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return dist.get_rank(group=self.process_group ) == 0 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict=torch.floataa ): """simple docstring""" _lowerCamelCase : List[Any] = torch.empty(__lowerCAmelCase , dtype=__lowerCAmelCase ) dist.scatter(__lowerCAmelCase , src=0 , scatter_list=__lowerCAmelCase , group=self.process_group ) return target_tensor def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : str = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _lowerCamelCase : int = next((addr for addr in addrs if addr.startswith('''e''' )) , __lowerCAmelCase ) return ifname def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : np.ndarray , __lowerCAmelCase : int ): """simple docstring""" if not dist.is_initialized(): _lowerCamelCase , _lowerCamelCase : List[str] = self._main_retrieve(__lowerCAmelCase , __lowerCAmelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCAmelCase ) # distributed training _lowerCamelCase : Tuple = dist.get_world_size(group=self.process_group ) # gather logic _lowerCamelCase : int = None if self._is_main(): _lowerCamelCase : Dict = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCAmelCase )] dist.gather(torch.tensor(__lowerCAmelCase ) , dst=0 , gather_list=__lowerCAmelCase , group=self.process_group ) # scatter logic _lowerCamelCase : List[Any] = question_hidden_states.shape[0] _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Any = [] if self._is_main(): assert len(__lowerCAmelCase ) == world_size _lowerCamelCase , _lowerCamelCase : Any = self._main_retrieve(torch.cat(__lowerCAmelCase ).numpy() , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = torch.tensor(__lowerCAmelCase ), torch.tensor(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = self._chunk_tensor(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Dict = self._chunk_tensor(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = self._scattered(__lowerCAmelCase , [n_queries, n_docs] , target_type=torch.intaa ) _lowerCamelCase : int = self._scattered(__lowerCAmelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCAmelCase )
83
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowerCAmelCase__ = '''<<<<<<< This should probably be modified because it mentions: ''' lowerCAmelCase__ = '''======= >>>>>>> ''' lowerCAmelCase__ = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] lowerCAmelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def snake_case_ ( A_ : Namespace ): '''simple docstring''' return ConvertCommand(args.tfds_path, args.datasets_directory ) class __snake_case ( _lowercase): @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : ArgumentParser ): """simple docstring""" _lowerCamelCase : List[str] = parser.add_parser( '''convert''' , help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.''' , ) train_parser.add_argument( '''--tfds_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.''' , ) train_parser.add_argument( '''--datasets_directory''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the HuggingFace Datasets folder.''' ) train_parser.set_defaults(func=__lowerCAmelCase ) def __init__( self : str , __lowerCAmelCase : str , __lowerCAmelCase : str , *__lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = get_logger('''datasets-cli/converting''' ) _lowerCamelCase : int = tfds_path _lowerCamelCase : Dict = datasets_directory def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if os.path.isdir(self._tfds_path ): _lowerCamelCase : Union[str, Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): _lowerCamelCase : Dict = os.path.dirname(self._tfds_path ) else: raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.''' ) _lowerCamelCase : int = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) _lowerCamelCase : str = [] _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Union[str, Any] = {} if os.path.isdir(self._tfds_path ): _lowerCamelCase : List[str] = os.listdir(__lowerCAmelCase ) else: _lowerCamelCase : Optional[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) _lowerCamelCase : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not os.path.isfile(__lowerCAmelCase ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('''Skipping file''' ) continue with open(__lowerCAmelCase , encoding='''utf-8''' ) as f: _lowerCamelCase : Tuple = f.readlines() _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Union[str, Any] = False _lowerCamelCase : int = False _lowerCamelCase : Tuple = [] for line in lines: _lowerCamelCase : Optional[int] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: _lowerCamelCase : Union[str, Any] = '''import datasets\n''' elif "import tensorflow" in out_line: # order is important here _lowerCamelCase : List[str] = '''''' continue elif "from absl import logging" in out_line: _lowerCamelCase : str = '''from datasets import logging\n''' elif "getLogger" in out_line: _lowerCamelCase : Union[str, Any] = out_line.replace('''getLogger''' , '''get_logger''' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): _lowerCamelCase : Dict = True _lowerCamelCase : Optional[int] = list(filter(lambda __lowerCAmelCase : e in out_line , __lowerCAmelCase ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(__lowerCAmelCase ) + '''\n''' ) out_lines.append(__lowerCAmelCase ) out_lines.append(__lowerCAmelCase ) continue else: for pattern, replacement in TO_CONVERT: _lowerCamelCase : str = re.sub(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: _lowerCamelCase : Dict = re.match(R'''from\stensorflow_datasets.*import\s([^\.\r\n]+)''' , __lowerCAmelCase ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(''',''' ) ) _lowerCamelCase : Union[str, Any] = '''from . import ''' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: _lowerCamelCase : Any = True out_lines.append(__lowerCAmelCase ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset _lowerCamelCase : Union[str, Any] = f_name.replace('''.py''' , '''''' ) _lowerCamelCase : List[str] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(__lowerCAmelCase ) if needs_manual_update: with_manual_update.append(__lowerCAmelCase ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.writelines(__lowerCAmelCase ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: _lowerCamelCase : Optional[int] = os.path.basename(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = imports_to_builder_map[f_name.replace('''.py''' , '''''' )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(__lowerCAmelCase , __lowerCAmelCase ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
83
1
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = '''hf-internal-testing/tiny-random-bert''' lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''') lowerCAmelCase__ = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6''' class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = cached_file(__lowerCAmelCase , __lowerCAmelCase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__lowerCAmelCase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : Optional[int] = f.read() self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) self.assertTrue(os.path.isfile(__lowerCAmelCase ) ) # File is cached at the same place the second time. _lowerCamelCase : Tuple = cached_file(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Using a specific revision to test the full commit hash. _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''9b8c223''' ) self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): _lowerCamelCase : Optional[int] = cached_file('''tiny-random-bert''' , __lowerCAmelCase ) with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): _lowerCamelCase : str = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''aaaa''' ) with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : int = cached_file(__lowerCAmelCase , '''conf''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , '''conf''' ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : List[Any] = f.read() self.assertTrue(os.path.isfile(os.path.join(__lowerCAmelCase , '''.no_exist''' , __lowerCAmelCase , '''conf''' ) ) ) _lowerCamelCase : str = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = cached_file(__lowerCAmelCase , '''conf''' , local_files_only=__lowerCAmelCase , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Any = mock.Mock() _lowerCamelCase : Optional[Any] = 5_0_0 _lowerCamelCase : Dict = {} _lowerCamelCase : List[Any] = HTTPError _lowerCamelCase : int = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__lowerCAmelCase ) as mock_head: _lowerCamelCase : Union[str, Any] = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_connection_errors=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __lowerCAmelCase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase , revision='''ahaha''' ) _lowerCamelCase : Dict = get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase ) # The name is the cached name which is not very easy to test, so instead we load the content. _lowerCamelCase : Dict = json.loads(open(__lowerCAmelCase , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = Path(__lowerCAmelCase ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__lowerCAmelCase , '''a.txt''' ) , str(__lowerCAmelCase ) ) self.assertIsNone(get_file_from_repo(__lowerCAmelCase , '''b.txt''' ) )
83
"""simple docstring""" def snake_case_ ( A_ : list, A_ : list, A_ : int, A_ : int, A_ : int ): '''simple docstring''' if index == number_of_items: return 0 _lowerCamelCase : int = 0 _lowerCamelCase : str = 0 _lowerCamelCase : Dict = knapsack(A_, A_, A_, A_, index + 1 ) if weights[index] <= max_weight: _lowerCamelCase : Tuple = values[index] + knapsack( A_, A_, A_, max_weight - weights[index], index + 1 ) return max(A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" lowerCAmelCase__ = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' lowerCAmelCase__ = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] lowerCAmelCase__ = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
83
"""simple docstring""" from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=_lowercase): snake_case__ : Optional[Any] = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : List[Any] ): """simple docstring""" requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , *__lowerCAmelCase : str , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : int , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
83
1
"""simple docstring""" from typing import List import numpy as np def snake_case_ ( A_ : dict ): '''simple docstring''' _lowerCamelCase : List[Any] = {key: len(A_ ) for key, value in gen_kwargs.items() if isinstance(A_, A_ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( '''Sharding is ambiguous for this dataset: ''' + '''we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n''' + '''\n'''.join(F'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() ) + '''\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ''' + '''and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.''' ) ) _lowerCamelCase : List[str] = max(lists_lengths.values(), default=0 ) return max(1, A_ ) def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' _lowerCamelCase : int = [] for group_idx in range(A_ ): _lowerCamelCase : Tuple = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break _lowerCamelCase : Any = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 _lowerCamelCase : List[str] = range(A_, start + num_shards_to_add ) shards_indices_per_group.append(A_ ) return shards_indices_per_group def snake_case_ ( A_ : dict, A_ : int ): '''simple docstring''' _lowerCamelCase : List[Any] = _number_of_shards_in_gen_kwargs(A_ ) if num_shards == 1: return [dict(A_ )] else: _lowerCamelCase : Union[str, Any] = _distribute_shards(num_shards=A_, max_num_jobs=A_ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(A_, A_ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(A_ ) ) ] def snake_case_ ( A_ : List[dict] ): '''simple docstring''' return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key], A_ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def snake_case_ ( A_ : np.random.Generator, A_ : dict ): '''simple docstring''' _lowerCamelCase : List[str] = {len(A_ ) for value in gen_kwargs.values() if isinstance(A_, A_ )} _lowerCamelCase : Tuple = {} for size in list_sizes: _lowerCamelCase : str = list(range(A_ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes _lowerCamelCase : Optional[int] = dict(A_ ) for key, value in shuffled_kwargs.items(): if isinstance(A_, A_ ): _lowerCamelCase : int = [value[i] for i in indices_per_size[len(A_ )]] return shuffled_kwargs
83
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __snake_case ( unittest.TestCase): @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Union[str, Any] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids _lowerCamelCase : Optional[int] = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids _lowerCamelCase : List[Any] = shift_tokens_right(__lowerCAmelCase , model.config.pad_token_id , model.config.decoder_start_token_id ) _lowerCamelCase : int = model(__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase ).logits _lowerCamelCase : Optional[Any] = optax.softmax_cross_entropy(__lowerCAmelCase , onehot(__lowerCAmelCase , logits.shape[-1] ) ).mean() _lowerCamelCase : Dict = -(labels.shape[-1] * loss.item()) _lowerCamelCase : Dict = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
83
1
"""simple docstring""" 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 __snake_case ( _lowercase): snake_case__ : List[Any] = "falcon" snake_case__ : Any = ["past_key_values"] def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=6_5_0_2_4 , __lowerCAmelCase : Optional[Any]=4_5_4_4 , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : List[Any]=7_1 , __lowerCAmelCase : Any=1E-5 , __lowerCAmelCase : Dict=0.02 , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Optional[int]=0.0 , __lowerCAmelCase : List[str]=0.0 , __lowerCAmelCase : int=None , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : int=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : int=1_1 , __lowerCAmelCase : Optional[Any]=1_1 , **__lowerCAmelCase : Dict , ): """simple docstring""" _lowerCamelCase : Union[str, Any] = vocab_size # Backward compatibility with n_embed kwarg _lowerCamelCase : Any = kwargs.pop('''n_embed''' , __lowerCAmelCase ) _lowerCamelCase : Tuple = hidden_size if n_embed is None else n_embed _lowerCamelCase : Optional[int] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Dict = layer_norm_epsilon _lowerCamelCase : int = initializer_range _lowerCamelCase : List[Any] = use_cache _lowerCamelCase : Tuple = hidden_dropout _lowerCamelCase : List[str] = attention_dropout _lowerCamelCase : List[str] = bos_token_id _lowerCamelCase : Optional[Any] = eos_token_id _lowerCamelCase : Optional[int] = num_attention_heads if num_kv_heads is None else num_kv_heads _lowerCamelCase : Optional[Any] = alibi _lowerCamelCase : str = new_decoder_architecture _lowerCamelCase : Union[str, Any] = multi_query # Ignored when new_decoder_architecture is True _lowerCamelCase : List[Any] = parallel_attn _lowerCamelCase : str = bias super().__init__(bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.hidden_size // self.num_attention_heads @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return not self.alibi
83
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''', [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ], ) def snake_case_ ( A_ : Dict, A_ : List[str] ): '''simple docstring''' _lowerCamelCase : int = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''', '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) _lowerCamelCase : str = DatasetInfosDict.from_directory(A_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''', [ DatasetInfo(), DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ), ], ) def snake_case_ ( A_ : str, A_ : DatasetInfo ): '''simple docstring''' _lowerCamelCase : Optional[Any] = str(A_ ) dataset_info.write_to_directory(A_ ) _lowerCamelCase : str = DatasetInfo.from_directory(A_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(A_, '''dataset_info.json''' ) ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = DatasetInfo( description='''foo''', citation='''bar''', homepage='''https://foo.bar''', license='''CC0''', features=Features({'''a''': Value('''int32''' )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train''', '''num_examples''': 42}], download_checksums={}, download_size=13_37, post_processing_size=4_42, dataset_size=12_34, size_in_bytes=13_37 + 4_42 + 12_34, ) _lowerCamelCase : Optional[Any] = dataset_info._to_yaml_dict() assert sorted(A_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) ) _lowerCamelCase : str = yaml.safe_dump(A_ ) _lowerCamelCase : Tuple = yaml.safe_load(A_ ) assert dataset_info_yaml_dict == reloaded def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : int = DatasetInfo() _lowerCamelCase : Dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''', [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=13_37 ), } ), ], ) def snake_case_ ( A_ : Optional[Any], A_ : DatasetInfosDict ): '''simple docstring''' _lowerCamelCase : List[str] = str(A_ ) dataset_infos_dict.write_to_directory(A_ ) _lowerCamelCase : List[Any] = DatasetInfosDict.from_directory(A_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _lowerCamelCase : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _lowerCamelCase : Any = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(A_, '''README.md''' ) )
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase__ = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''MobileViTFeatureExtractor'''] lowerCAmelCase__ = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __snake_case : def __init__( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : List[str]=2_4 , __lowerCAmelCase : str=1_6 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : int=4 , __lowerCAmelCase : int=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : List[Any]=0.02 , __lowerCAmelCase : str=None , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Union[str, Any]=2 , ): """simple docstring""" _lowerCamelCase : List[str] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : Tuple = patch_size _lowerCamelCase : Optional[int] = max_length _lowerCamelCase : List[Any] = num_mel_bins _lowerCamelCase : int = is_training _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : Dict = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : List[str] = scope _lowerCamelCase : Optional[int] = frequency_stride _lowerCamelCase : List[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowerCamelCase : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _lowerCamelCase : Union[str, Any] = (self.max_length - self.patch_size) // self.time_stride + 1 _lowerCamelCase : Any = frequency_out_dimension * time_out_dimension _lowerCamelCase : List[Any] = num_patches + 2 def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Optional[int] = self.get_config() return config, input_values, labels def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = ASTModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Optional[Any] = config_and_inputs _lowerCamelCase : int = {'''input_values''': input_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Any = False snake_case__ : List[Any] = False snake_case__ : Optional[Any] = False snake_case__ : Optional[Any] = False def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[int] = ASTModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCamelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : str = ['''input_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Union[str, Any] = ASTModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' ) _lowerCamelCase , _lowerCamelCase : str = torchaudio.load(A_ ) return audio, sampling_rate @require_torch @require_torchaudio class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.default_feature_extractor _lowerCamelCase : Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = self.default_feature_extractor _lowerCamelCase , _lowerCamelCase : List[Any] = prepare_audio() _lowerCamelCase : Dict = audio.squeeze().numpy() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , sampling_rate=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Tuple = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : Tuple = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
83
1
"""simple docstring""" from __future__ import annotations from scipy.special import comb # type: ignore class __snake_case : def __init__( self : Union[str, Any] , __lowerCAmelCase : list[tuple[float, float]] ): """simple docstring""" _lowerCamelCase : Any = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. _lowerCamelCase : Any = len(__lowerCAmelCase ) - 1 def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : float ): """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." _lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , __lowerCAmelCase ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(__lowerCAmelCase ) , 5 ) == 1 return output_values def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : float ): """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." _lowerCamelCase : Optional[int] = self.basis_function(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = 0.0 _lowerCamelCase : Any = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : float = 0.01 ): """simple docstring""" from matplotlib import pyplot as plt # type: ignore _lowerCamelCase : list[float] = [] # x coordinates of points to plot _lowerCamelCase : list[float] = [] # y coordinates of points to plot _lowerCamelCase : List[Any] = 0.0 while t <= 1: _lowerCamelCase : List[Any] = self.bezier_curve_function(__lowerCAmelCase ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size _lowerCamelCase : List[str] = [i[0] for i in self.list_of_points] _lowerCamelCase : Optional[int] = [i[1] for i in self.list_of_points] plt.plot( __lowerCAmelCase , __lowerCAmelCase , color='''blue''' , label='''Curve of Degree ''' + str(self.degree ) , ) plt.scatter(__lowerCAmelCase , __lowerCAmelCase , color='''red''' , label='''Control Points''' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
83
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( A_ : Dict, A_ : bool = True, A_ : float = math.inf, A_ : float = -math.inf, A_ : float = math.inf, A_ : float = -math.inf, A_ : bool = False, A_ : float = 1_00, A_ : float = 0.01, A_ : float = 1, ): '''simple docstring''' _lowerCamelCase : Optional[int] = False _lowerCamelCase : str = search_prob _lowerCamelCase : str = start_temperate _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : int = 0 _lowerCamelCase : Any = None while not search_end: _lowerCamelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCamelCase : Tuple = current_state scores.append(A_ ) iterations += 1 _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCamelCase : List[Any] = random.randint(0, len(A_ ) - 1 ) # picking a random neighbor _lowerCamelCase : Dict = neighbors.pop(A_ ) _lowerCamelCase : Union[str, Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCamelCase : Optional[Any] = picked_neighbor else: _lowerCamelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCamelCase : Union[str, Any] = picked_neighbor _lowerCamelCase : List[str] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCamelCase : Tuple = True else: _lowerCamelCase : Optional[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A_ ), A_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def snake_case_ ( A_ : Optional[int], A_ : List[Any] ): '''simple docstring''' return (3 * x**2) - (6 * y) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
83
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def snake_case_ ( A_ : Any ): '''simple docstring''' _lowerCamelCase : List[str] = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: _lowerCamelCase : Union[str, Any] = [1_44, 1_92, 2_40] _lowerCamelCase : Tuple = [16, 32, 64, 96, 1_28, 1_60, 6_40] elif "mobilevit_xs" in mobilevit_name: _lowerCamelCase : List[Any] = [96, 1_20, 1_44] _lowerCamelCase : Dict = [16, 32, 48, 64, 80, 96, 3_84] elif "mobilevit_xxs" in mobilevit_name: _lowerCamelCase : Union[str, Any] = [64, 80, 96] _lowerCamelCase : Optional[int] = [16, 16, 24, 48, 64, 80, 3_20] _lowerCamelCase : Tuple = 0.05 _lowerCamelCase : Tuple = 2.0 if mobilevit_name.startswith('''deeplabv3_''' ): _lowerCamelCase : int = 5_12 _lowerCamelCase : Union[str, Any] = 16 _lowerCamelCase : Optional[Any] = 21 _lowerCamelCase : Tuple = '''pascal-voc-id2label.json''' else: _lowerCamelCase : List[Any] = 10_00 _lowerCamelCase : str = '''imagenet-1k-id2label.json''' _lowerCamelCase : Optional[int] = '''huggingface/label-files''' _lowerCamelCase : Any = json.load(open(hf_hub_download(A_, A_, repo_type='''dataset''' ), '''r''' ) ) _lowerCamelCase : int = {int(A_ ): v for k, v in idalabel.items()} _lowerCamelCase : Any = idalabel _lowerCamelCase : str = {v: k for k, v in idalabel.items()} return config def snake_case_ ( A_ : Tuple, A_ : Union[str, Any]=False ): '''simple docstring''' for i in range(1, 6 ): if F'''layer_{i}.''' in name: _lowerCamelCase : str = name.replace(F'''layer_{i}.''', F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: _lowerCamelCase : Union[str, Any] = name.replace('''conv_1.''', '''conv_stem.''' ) if ".block." in name: _lowerCamelCase : Union[str, Any] = name.replace('''.block.''', '''.''' ) if "exp_1x1" in name: _lowerCamelCase : str = name.replace('''exp_1x1''', '''expand_1x1''' ) if "red_1x1" in name: _lowerCamelCase : Dict = name.replace('''red_1x1''', '''reduce_1x1''' ) if ".local_rep.conv_3x3." in name: _lowerCamelCase : List[Any] = name.replace('''.local_rep.conv_3x3.''', '''.conv_kxk.''' ) if ".local_rep.conv_1x1." in name: _lowerCamelCase : Optional[int] = name.replace('''.local_rep.conv_1x1.''', '''.conv_1x1.''' ) if ".norm." in name: _lowerCamelCase : Tuple = name.replace('''.norm.''', '''.normalization.''' ) if ".conv." in name: _lowerCamelCase : Optional[int] = name.replace('''.conv.''', '''.convolution.''' ) if ".conv_proj." in name: _lowerCamelCase : str = name.replace('''.conv_proj.''', '''.conv_projection.''' ) for i in range(0, 2 ): for j in range(0, 4 ): if F'''.{i}.{j}.''' in name: _lowerCamelCase : str = name.replace(F'''.{i}.{j}.''', F'''.{i}.layer.{j}.''' ) for i in range(2, 6 ): for j in range(0, 4 ): if F'''.{i}.{j}.''' in name: _lowerCamelCase : Optional[int] = name.replace(F'''.{i}.{j}.''', F'''.{i}.''' ) if "expand_1x1" in name: _lowerCamelCase : Union[str, Any] = name.replace('''expand_1x1''', '''downsampling_layer.expand_1x1''' ) if "conv_3x3" in name: _lowerCamelCase : Tuple = name.replace('''conv_3x3''', '''downsampling_layer.conv_3x3''' ) if "reduce_1x1" in name: _lowerCamelCase : List[str] = name.replace('''reduce_1x1''', '''downsampling_layer.reduce_1x1''' ) for i in range(2, 5 ): if F'''.global_rep.{i}.weight''' in name: _lowerCamelCase : Optional[Any] = name.replace(F'''.global_rep.{i}.weight''', '''.layernorm.weight''' ) if F'''.global_rep.{i}.bias''' in name: _lowerCamelCase : Union[str, Any] = name.replace(F'''.global_rep.{i}.bias''', '''.layernorm.bias''' ) if ".global_rep." in name: _lowerCamelCase : int = name.replace('''.global_rep.''', '''.transformer.''' ) if ".pre_norm_mha.0." in name: _lowerCamelCase : Dict = name.replace('''.pre_norm_mha.0.''', '''.layernorm_before.''' ) if ".pre_norm_mha.1.out_proj." in name: _lowerCamelCase : Optional[int] = name.replace('''.pre_norm_mha.1.out_proj.''', '''.attention.output.dense.''' ) if ".pre_norm_ffn.0." in name: _lowerCamelCase : int = name.replace('''.pre_norm_ffn.0.''', '''.layernorm_after.''' ) if ".pre_norm_ffn.1." in name: _lowerCamelCase : Tuple = name.replace('''.pre_norm_ffn.1.''', '''.intermediate.dense.''' ) if ".pre_norm_ffn.4." in name: _lowerCamelCase : Optional[Any] = name.replace('''.pre_norm_ffn.4.''', '''.output.dense.''' ) if ".transformer." in name: _lowerCamelCase : List[str] = name.replace('''.transformer.''', '''.transformer.layer.''' ) if ".aspp_layer." in name: _lowerCamelCase : Optional[Any] = name.replace('''.aspp_layer.''', '''.''' ) if ".aspp_pool." in name: _lowerCamelCase : Tuple = name.replace('''.aspp_pool.''', '''.''' ) if "seg_head." in name: _lowerCamelCase : Dict = name.replace('''seg_head.''', '''segmentation_head.''' ) if "segmentation_head.classifier.classifier." in name: _lowerCamelCase : Dict = name.replace('''segmentation_head.classifier.classifier.''', '''segmentation_head.classifier.''' ) if "classifier.fc." in name: _lowerCamelCase : int = name.replace('''classifier.fc.''', '''classifier.''' ) elif (not base_model) and ("segmentation_head." not in name): _lowerCamelCase : str = '''mobilevit.''' + name return name def snake_case_ ( A_ : Union[str, Any], A_ : str, A_ : Union[str, Any]=False ): '''simple docstring''' if base_model: _lowerCamelCase : Union[str, Any] = '''''' else: _lowerCamelCase : Tuple = '''mobilevit.''' for key in orig_state_dict.copy().keys(): _lowerCamelCase : Optional[int] = orig_state_dict.pop(A_ ) if key[:8] == "encoder.": _lowerCamelCase : List[str] = key[8:] if "qkv" in key: _lowerCamelCase : Tuple = key.split('''.''' ) _lowerCamelCase : str = int(key_split[0][6:] ) - 1 _lowerCamelCase : str = int(key_split[3] ) _lowerCamelCase : str = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) _lowerCamelCase : List[str] = layer.transformer.layer[transformer_num].attention.attention.all_head_size _lowerCamelCase : Tuple = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: _lowerCamelCase : List[str] = val[:dim, :] _lowerCamelCase : Optional[Any] = val[dim : dim * 2, :] _lowerCamelCase : str = val[-dim:, :] else: _lowerCamelCase : List[Any] = val[:dim] _lowerCamelCase : Dict = val[dim : dim * 2] _lowerCamelCase : Any = val[-dim:] else: _lowerCamelCase : List[Any] = val return orig_state_dict def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _lowerCamelCase : str = Image.open(requests.get(A_, stream=A_ ).raw ) return im @torch.no_grad() def snake_case_ ( A_ : Any, A_ : Tuple, A_ : Tuple, A_ : Any=False ): '''simple docstring''' _lowerCamelCase : Any = get_mobilevit_config(A_ ) # load original state_dict _lowerCamelCase : Union[str, Any] = torch.load(A_, map_location='''cpu''' ) # load 🤗 model if mobilevit_name.startswith('''deeplabv3_''' ): _lowerCamelCase : int = MobileViTForSemanticSegmentation(A_ ).eval() else: _lowerCamelCase : Optional[int] = MobileViTForImageClassification(A_ ).eval() _lowerCamelCase : List[str] = convert_state_dict(A_, A_ ) model.load_state_dict(A_ ) # Check outputs on an image, prepared by MobileViTImageProcessor _lowerCamelCase : str = MobileViTImageProcessor(crop_size=config.image_size, size=config.image_size + 32 ) _lowerCamelCase : Optional[Any] = image_processor(images=prepare_img(), return_tensors='''pt''' ) _lowerCamelCase : int = model(**A_ ) _lowerCamelCase : Any = outputs.logits if mobilevit_name.startswith('''deeplabv3_''' ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": _lowerCamelCase : List[Any] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": _lowerCamelCase : List[str] = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": _lowerCamelCase : str = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3], A_, atol=1E-4 ) else: assert logits.shape == (1, 10_00) if mobilevit_name == "mobilevit_s": _lowerCamelCase : Dict = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": _lowerCamelCase : Optional[int] = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": _lowerCamelCase : Optional[Any] = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3], A_, atol=1E-4 ) Path(A_ ).mkdir(exist_ok=A_ ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A_ ) if push_to_hub: _lowerCamelCase : Any = { '''mobilevit_s''': '''mobilevit-small''', '''mobilevit_xs''': '''mobilevit-x-small''', '''mobilevit_xxs''': '''mobilevit-xx-small''', '''deeplabv3_mobilevit_s''': '''deeplabv3-mobilevit-small''', '''deeplabv3_mobilevit_xs''': '''deeplabv3-mobilevit-x-small''', '''deeplabv3_mobilevit_xxs''': '''deeplabv3-mobilevit-xx-small''', } print('''Pushing to the hub...''' ) _lowerCamelCase : Tuple = model_mapping[mobilevit_name] image_processor.push_to_hub(A_, organization='''apple''' ) model.push_to_hub(A_, organization='''apple''' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--mobilevit_name''', default='''mobilevit_s''', type=str, help=( '''Name of the MobileViT model you\'d like to convert. Should be one of \'mobilevit_s\', \'mobilevit_xs\',''' ''' \'mobilevit_xxs\', \'deeplabv3_mobilevit_s\', \'deeplabv3_mobilevit_xs\', \'deeplabv3_mobilevit_xxs\'.''' ), ) parser.add_argument( '''--checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) lowerCAmelCase__ = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
83
"""simple docstring""" from collections import namedtuple lowerCAmelCase__ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase__ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def snake_case_ ( A_ : float, A_ : str, A_ : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ''', '''.join(A_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ''', '''.join(A_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase__ = { '''configuration_roc_bert''': ['''ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoCBertConfig'''], '''tokenization_roc_bert''': ['''RoCBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoCBertForCausalLM''', '''RoCBertForMaskedLM''', '''RoCBertForMultipleChoice''', '''RoCBertForPreTraining''', '''RoCBertForQuestionAnswering''', '''RoCBertForSequenceClassification''', '''RoCBertForTokenClassification''', '''RoCBertLayer''', '''RoCBertModel''', '''RoCBertPreTrainedModel''', '''load_tf_weights_in_roc_bert''', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case ( _lowercase): def __init__( self : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=9_9 , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : Optional[int]=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : int=5_1_2 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any="None" , __lowerCAmelCase : str=3 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[Any]=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Dict = use_input_mask _lowerCamelCase : Tuple = use_token_type_ids _lowerCamelCase : Optional[Any] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Optional[int] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : int = relative_attention _lowerCamelCase : Union[str, Any] = position_biased_input _lowerCamelCase : str = pos_att_type _lowerCamelCase : Tuple = scope def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : int = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : str = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : List[Any] = model(__lowerCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : Dict = DebertaVaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : Tuple = DebertaVaForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = DebertaVaForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : int = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True snake_case__ : List[Any] = False snake_case__ : int = False snake_case__ : Optional[Any] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) _lowerCamelCase : List[str] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] # compare the actual values for a slice. _lowerCamelCase : Union[str, Any] = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
83
1
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : list[list[int]] ): '''simple docstring''' for i in range(1, len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(A_ ) ): for j in range(1, len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = '''hf-internal-testing/tiny-random-bert''' lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''') lowerCAmelCase__ = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6''' class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = cached_file(__lowerCAmelCase , __lowerCAmelCase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__lowerCAmelCase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : Optional[int] = f.read() self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) self.assertTrue(os.path.isfile(__lowerCAmelCase ) ) # File is cached at the same place the second time. _lowerCamelCase : Tuple = cached_file(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Using a specific revision to test the full commit hash. _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''9b8c223''' ) self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): _lowerCamelCase : Optional[int] = cached_file('''tiny-random-bert''' , __lowerCAmelCase ) with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): _lowerCamelCase : str = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''aaaa''' ) with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : int = cached_file(__lowerCAmelCase , '''conf''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , '''conf''' ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : List[Any] = f.read() self.assertTrue(os.path.isfile(os.path.join(__lowerCAmelCase , '''.no_exist''' , __lowerCAmelCase , '''conf''' ) ) ) _lowerCamelCase : str = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = cached_file(__lowerCAmelCase , '''conf''' , local_files_only=__lowerCAmelCase , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Any = mock.Mock() _lowerCamelCase : Optional[Any] = 5_0_0 _lowerCamelCase : Dict = {} _lowerCamelCase : List[Any] = HTTPError _lowerCamelCase : int = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__lowerCAmelCase ) as mock_head: _lowerCamelCase : Union[str, Any] = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_connection_errors=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __lowerCAmelCase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase , revision='''ahaha''' ) _lowerCamelCase : Dict = get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase ) # The name is the cached name which is not very easy to test, so instead we load the content. _lowerCamelCase : Dict = json.loads(open(__lowerCAmelCase , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = Path(__lowerCAmelCase ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__lowerCAmelCase , '''a.txt''' ) , str(__lowerCAmelCase ) ) self.assertIsNone(get_file_from_repo(__lowerCAmelCase , '''b.txt''' ) )
83
1
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __snake_case : def __init__( self : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int]=sys.maxsize ): """simple docstring""" _lowerCamelCase : Tuple = '''bilinear''' _lowerCamelCase : Union[str, Any] = max_size _lowerCamelCase : Optional[Any] = short_edge_length def __call__( self : Optional[Any] , __lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : Any = [] for img in imgs: _lowerCamelCase , _lowerCamelCase : Optional[Any] = img.shape[:2] # later: provide list and randomly choose index for resize _lowerCamelCase : Optional[int] = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img _lowerCamelCase : str = size * 1.0 / min(__lowerCAmelCase , __lowerCAmelCase ) if h < w: _lowerCamelCase , _lowerCamelCase : Optional[Any] = size, scale * w else: _lowerCamelCase , _lowerCamelCase : List[str] = scale * h, size if max(__lowerCAmelCase , __lowerCAmelCase ) > self.max_size: _lowerCamelCase : Optional[int] = self.max_size * 1.0 / max(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : int = newh * scale _lowerCamelCase : Tuple = neww * scale _lowerCamelCase : Union[str, Any] = int(neww + 0.5 ) _lowerCamelCase : List[str] = int(newh + 0.5 ) if img.dtype == np.uinta: _lowerCamelCase : int = Image.fromarray(__lowerCAmelCase ) _lowerCamelCase : int = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) _lowerCamelCase : List[str] = np.asarray(__lowerCAmelCase ) else: _lowerCamelCase : List[str] = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw _lowerCamelCase : Any = nn.functional.interpolate( __lowerCAmelCase , (newh, neww) , mode=self.interp_method , align_corners=__lowerCAmelCase ).squeeze(0 ) img_augs.append(__lowerCAmelCase ) return img_augs class __snake_case : def __init__( self : Union[str, Any] , __lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : str = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) _lowerCamelCase : Optional[int] = cfg.INPUT.FORMAT _lowerCamelCase : str = cfg.SIZE_DIVISIBILITY _lowerCamelCase : int = cfg.PAD_VALUE _lowerCamelCase : List[Any] = cfg.INPUT.MAX_SIZE_TEST _lowerCamelCase : Union[str, Any] = cfg.MODEL.DEVICE _lowerCamelCase : Tuple = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _lowerCamelCase : Tuple = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _lowerCamelCase : int = lambda __lowerCAmelCase : (x - self.pixel_mean) / self.pixel_std def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = tuple(max(__lowerCAmelCase ) for s in zip(*[img.shape for img in images] ) ) _lowerCamelCase : Any = [im.shape[-2:] for im in images] _lowerCamelCase : int = [ nn.functional.pad( __lowerCAmelCase , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(__lowerCAmelCase , __lowerCAmelCase ) ] return torch.stack(__lowerCAmelCase ), torch.tensor(__lowerCAmelCase ) def __call__( self : Any , __lowerCAmelCase : List[str] , __lowerCAmelCase : Any=False ): """simple docstring""" with torch.no_grad(): if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): _lowerCamelCase : List[Any] = [images] if single_image: assert len(__lowerCAmelCase ) == 1 for i in range(len(__lowerCAmelCase ) ): if isinstance(images[i] , torch.Tensor ): images.insert(__lowerCAmelCase , images.pop(__lowerCAmelCase ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( __lowerCAmelCase , torch.as_tensor(img_tensorize(images.pop(__lowerCAmelCase ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge _lowerCamelCase : Dict = torch.tensor([im.shape[:2] for im in images] ) _lowerCamelCase : str = self.aug(__lowerCAmelCase ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic _lowerCamelCase : Optional[int] = [self.normalizer(__lowerCAmelCase ) for x in images] # now pad them to do the following operations _lowerCamelCase , _lowerCamelCase : Dict = self.pad(__lowerCAmelCase ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad _lowerCamelCase : Union[str, Any] = torch.true_divide(__lowerCAmelCase , __lowerCAmelCase ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def snake_case_ ( A_ : Optional[int], A_ : Any ): '''simple docstring''' boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def snake_case_ ( A_ : str, A_ : Tuple[int, int] ): '''simple docstring''' assert torch.isfinite(A_ ).all(), "Box tensor contains infinite or NaN!" _lowerCamelCase , _lowerCamelCase : Union[str, Any] = box_size tensor[:, 0].clamp_(min=0, max=A_ ) tensor[:, 1].clamp_(min=0, max=A_ ) tensor[:, 2].clamp_(min=0, max=A_ ) tensor[:, 3].clamp_(min=0, max=A_ )
83
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( _lowercase): snake_case__ : List[str] = "cvt" def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=3 , __lowerCAmelCase : List[str]=[7, 3, 3] , __lowerCAmelCase : int=[4, 2, 2] , __lowerCAmelCase : int=[2, 1, 1] , __lowerCAmelCase : str=[6_4, 1_9_2, 3_8_4] , __lowerCAmelCase : Dict=[1, 3, 6] , __lowerCAmelCase : Optional[Any]=[1, 2, 1_0] , __lowerCAmelCase : Dict=[4.0, 4.0, 4.0] , __lowerCAmelCase : Dict=[0.0, 0.0, 0.0] , __lowerCAmelCase : Union[str, Any]=[0.0, 0.0, 0.0] , __lowerCAmelCase : int=[0.0, 0.0, 0.1] , __lowerCAmelCase : Union[str, Any]=[True, True, True] , __lowerCAmelCase : str=[False, False, True] , __lowerCAmelCase : List[str]=["dw_bn", "dw_bn", "dw_bn"] , __lowerCAmelCase : List[Any]=[3, 3, 3] , __lowerCAmelCase : Dict=[1, 1, 1] , __lowerCAmelCase : str=[2, 2, 2] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Any=1E-12 , **__lowerCAmelCase : int , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : int = patch_sizes _lowerCamelCase : Optional[Any] = patch_stride _lowerCamelCase : str = patch_padding _lowerCamelCase : Any = embed_dim _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Dict = depth _lowerCamelCase : Optional[int] = mlp_ratio _lowerCamelCase : Any = attention_drop_rate _lowerCamelCase : Any = drop_rate _lowerCamelCase : Dict = drop_path_rate _lowerCamelCase : Optional[int] = qkv_bias _lowerCamelCase : int = cls_token _lowerCamelCase : int = qkv_projection_method _lowerCamelCase : Optional[Any] = kernel_qkv _lowerCamelCase : List[str] = padding_kv _lowerCamelCase : Tuple = stride_kv _lowerCamelCase : Union[str, Any] = padding_q _lowerCamelCase : Optional[Any] = stride_q _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps
83
1
"""simple docstring""" import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' _lowerCamelCase : Optional[Any] = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'''encoder.deit.blocks.{i}.norm1.weight''', F'''encoder.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''encoder.deit.blocks.{i}.norm1.bias''', F'''encoder.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.attn.proj.weight''', F'''encoder.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.attn.proj.bias''', F'''encoder.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.norm2.weight''', F'''encoder.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''encoder.deit.blocks.{i}.norm2.bias''', F'''encoder.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.mlp.fc1.weight''', F'''encoder.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.mlp.fc1.bias''', F'''encoder.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.mlp.fc2.weight''', F'''encoder.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''encoder.deit.blocks.{i}.mlp.fc2.bias''', F'''encoder.encoder.layer.{i}.output.dense.bias''') ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ('''encoder.deit.cls_token''', '''encoder.embeddings.cls_token'''), ('''encoder.deit.pos_embed''', '''encoder.embeddings.position_embeddings'''), ('''encoder.deit.patch_embed.proj.weight''', '''encoder.embeddings.patch_embeddings.projection.weight'''), ('''encoder.deit.patch_embed.proj.bias''', '''encoder.embeddings.patch_embeddings.projection.bias'''), ('''encoder.deit.norm.weight''', '''encoder.layernorm.weight'''), ('''encoder.deit.norm.bias''', '''encoder.layernorm.bias'''), ] ) return rename_keys def snake_case_ ( A_ : List[Any], A_ : Tuple ): '''simple docstring''' for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) _lowerCamelCase : Any = state_dict.pop(F'''encoder.deit.blocks.{i}.attn.qkv.weight''' ) _lowerCamelCase : Dict = in_proj_weight[ : encoder_config.hidden_size, : ] _lowerCamelCase : Dict = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] _lowerCamelCase : str = in_proj_weight[ -encoder_config.hidden_size :, : ] def snake_case_ ( A_ : List[str], A_ : int, A_ : int ): '''simple docstring''' _lowerCamelCase : str = dct.pop(A_ ) _lowerCamelCase : str = val def snake_case_ ( A_ : Dict ): '''simple docstring''' if "handwritten" in checkpoint_url: _lowerCamelCase : int = '''https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg''' # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: _lowerCamelCase : List[str] = '''https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg''' _lowerCamelCase : Dict = Image.open(requests.get(A_, stream=A_ ).raw ).convert('''RGB''' ) return im @torch.no_grad() def snake_case_ ( A_ : Tuple, A_ : Dict ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = ViTConfig(image_size=3_84, qkv_bias=A_ ) _lowerCamelCase : int = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: _lowerCamelCase : Any = 7_68 elif "large" in checkpoint_url: # use ViT-large encoder _lowerCamelCase : str = 10_24 _lowerCamelCase : List[str] = 40_96 _lowerCamelCase : Any = 24 _lowerCamelCase : Union[str, Any] = 16 _lowerCamelCase : str = 10_24 else: raise ValueError('''Should either find \'base\' or \'large\' in checkpoint URL''' ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: _lowerCamelCase : Tuple = False _lowerCamelCase : Any = '''relu''' _lowerCamelCase : Optional[Any] = 10_24 _lowerCamelCase : List[str] = True _lowerCamelCase : Tuple = False _lowerCamelCase : Tuple = False # load HuggingFace model _lowerCamelCase : List[Any] = ViTModel(A_, add_pooling_layer=A_ ) _lowerCamelCase : List[str] = TrOCRForCausalLM(A_ ) _lowerCamelCase : List[Any] = VisionEncoderDecoderModel(encoder=A_, decoder=A_ ) model.eval() # load state_dict of original model, rename some keys _lowerCamelCase : Optional[int] = torch.hub.load_state_dict_from_url(A_, map_location='''cpu''', check_hash=A_ )['''model'''] _lowerCamelCase : Tuple = create_rename_keys(A_, A_ ) for src, dest in rename_keys: rename_key(A_, A_, A_ ) read_in_q_k_v(A_, A_ ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): _lowerCamelCase : Union[str, Any] = state_dict.pop(A_ ) if key.startswith('''decoder''' ) and "output_projection" not in key: _lowerCamelCase : Dict = val else: _lowerCamelCase : Dict = val # load state dict model.load_state_dict(A_ ) # Check outputs on an image _lowerCamelCase : str = ViTImageProcessor(size=encoder_config.image_size ) _lowerCamelCase : List[str] = RobertaTokenizer.from_pretrained('''roberta-large''' ) _lowerCamelCase : List[str] = TrOCRProcessor(A_, A_ ) _lowerCamelCase : Dict = processor(images=prepare_img(A_ ), return_tensors='''pt''' ).pixel_values # verify logits _lowerCamelCase : str = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) _lowerCamelCase : Tuple = model(pixel_values=A_, decoder_input_ids=A_ ) _lowerCamelCase : Optional[Any] = outputs.logits _lowerCamelCase : str = torch.Size([1, 1, 5_02_65] ) if "trocr-base-handwritten" in checkpoint_url: _lowerCamelCase : Dict = torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: _lowerCamelCase : Optional[int] = torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: _lowerCamelCase : Tuple = torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: _lowerCamelCase : Tuple = torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10], A_, atol=1E-3 ), "First elements of logits not as expected" Path(A_ ).mkdir(exist_ok=A_ ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt''', type=str, help='''URL to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) lowerCAmelCase__ = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
83
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __snake_case ( _lowercase): snake_case__ : torch.FloatTensor snake_case__ : torch.FloatTensor class __snake_case ( _lowercase , _lowercase): snake_case__ : int = 1 @register_to_config def __init__( self : str , __lowerCAmelCase : int = 2_0_0_0 , __lowerCAmelCase : float = 0.15 , __lowerCAmelCase : float = 0.01 , __lowerCAmelCase : float = 13_48.0 , __lowerCAmelCase : float = 1E-5 , __lowerCAmelCase : int = 1 , ): """simple docstring""" _lowerCamelCase : Optional[int] = sigma_max # setable values _lowerCamelCase : Dict = None self.set_sigmas(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : Union[str, torch.device] = None ): """simple docstring""" _lowerCamelCase : Tuple = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCamelCase : Optional[int] = torch.linspace(1 , __lowerCAmelCase , __lowerCAmelCase , device=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None ): """simple docstring""" _lowerCamelCase : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCamelCase : int = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCamelCase : Optional[int] = torch.exp(torch.linspace(math.log(__lowerCAmelCase ) , math.log(__lowerCAmelCase ) , __lowerCAmelCase ) ) _lowerCamelCase : Tuple = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : int , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) _lowerCamelCase : Tuple = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCamelCase : Dict = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCamelCase : Optional[int] = timesteps.to(self.discrete_sigmas.device ) _lowerCamelCase : Any = self.discrete_sigmas[timesteps].to(sample.device ) _lowerCamelCase : int = self.get_adjacent_sigma(__lowerCAmelCase , __lowerCAmelCase ).to(sample.device ) _lowerCamelCase : Any = torch.zeros_like(__lowerCAmelCase ) _lowerCamelCase : Any = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCamelCase : Union[str, Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): _lowerCamelCase : List[Any] = diffusion.unsqueeze(-1 ) _lowerCamelCase : int = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCamelCase : List[str] = randn_tensor( sample.shape , layout=sample.layout , generator=__lowerCAmelCase , device=sample.device , dtype=sample.dtype ) _lowerCamelCase : List[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCamelCase : int = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=__lowerCAmelCase , prev_sample_mean=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCamelCase : Union[str, Any] = randn_tensor(sample.shape , layout=sample.layout , generator=__lowerCAmelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr _lowerCamelCase : Union[str, Any] = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : str = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCamelCase : Tuple = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): _lowerCamelCase : str = step_size.unsqueeze(-1 ) _lowerCamelCase : Any = sample + step_size * model_output _lowerCamelCase : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , ): """simple docstring""" _lowerCamelCase : Dict = timesteps.to(original_samples.device ) _lowerCamelCase : Union[str, Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] _lowerCamelCase : Union[str, Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(__lowerCAmelCase ) * sigmas[:, None, None, None] ) _lowerCamelCase : int = noise + original_samples return noisy_samples def __len__( self : Optional[int] ): """simple docstring""" return self.config.num_train_timesteps
83
1
"""simple docstring""" import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __snake_case ( _lowercase , unittest.TestCase): snake_case__ : Optional[int] = DebertaTokenizer snake_case__ : Optional[int] = True snake_case__ : Dict = DebertaTokenizerFast def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _lowerCamelCase : Any = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] _lowerCamelCase : Any = dict(zip(__lowerCAmelCase , range(len(__lowerCAmelCase ) ) ) ) _lowerCamelCase : Dict = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] _lowerCamelCase : Dict = {'''unk_token''': '''[UNK]'''} _lowerCamelCase : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _lowerCamelCase : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__lowerCAmelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple , **__lowerCAmelCase : Any ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : str = '''lower newer''' _lowerCamelCase : Any = '''lower newer''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.get_tokenizer() _lowerCamelCase : List[Any] = '''lower newer''' _lowerCamelCase : int = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] _lowerCamelCase : Tuple = tokenizer.tokenize(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = tokens + [tokenizer.unk_token] _lowerCamelCase : Optional[Any] = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = self.get_tokenizer() _lowerCamelCase : List[Any] = tokenizer('''Hello''' , '''World''' ) _lowerCamelCase : Any = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , __lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) _lowerCamelCase : List[str] = tokenizer.encode('''sequence builders''' , add_special_tokens=__lowerCAmelCase ) _lowerCamelCase : List[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__lowerCAmelCase ) _lowerCamelCase : List[Any] = tokenizer.encode( '''sequence builders''' , add_special_tokens=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase ) _lowerCamelCase : List[Any] = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase ) _lowerCamelCase : List[Any] = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase , __lowerCAmelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: _lowerCamelCase : List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) _lowerCamelCase : Optional[Any] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] _lowerCamelCase : Optional[int] = tokenizer(__lowerCAmelCase , padding=__lowerCAmelCase ) _lowerCamelCase : Tuple = [tokenizer.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) for seq in encoding['''input_ids''']] # fmt: off _lowerCamelCase : Any = { '''input_ids''': [ [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 3_5, 8_3, 2_5_1_9_1, 1_6_3, 1_8_8_5_4, 1_3, 1_2_1_5_6, 1_2, 1_6_1_0_1, 2_5_3_7_6, 1_3_8_0_7, 9, 2_2_2_0_5, 2_7_8_9_3, 1_6_3_5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 2_4_5_3_6, 8_0, 4_3_7_9_7, 4_8_7_8, 7_3_7_3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_3_3, 7_8, 6_5, 1_6, 1_0, 3_7_2_4, 1_5_3_8, 3_3_1_8_3, 1_1_3_0_3, 4_3_7_9_7, 1_9_3_8, 4, 8_7_0, 2_4_1_6_5, 2_9_1_0_5, 5, 7_3_9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 3_6_1_7_3, 8_8, 8_0, 6_5_0, 7_8_2_1, 4_5_9_4_0, 6, 5_2, 2_5_5_9, 5, 1_8_3_6, 9, 5, 7_3_9_7, 1_3_1_7_1, 3_1, 5, 1_8_3_6, 9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on _lowerCamelCase : Any = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , __lowerCAmelCase ) for expected, decoded in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertEqual(__lowerCAmelCase , __lowerCAmelCase )
83
"""simple docstring""" from torch import nn def snake_case_ ( A_ : int ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'''Unsupported activation function: {act_fn}''' )
83
1
"""simple docstring""" def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Optional[int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] _lowerCamelCase : Tuple = 6 _lowerCamelCase : int = 1 _lowerCamelCase : Any = 19_01 _lowerCamelCase : int = 0 while year < 20_01: day += 7 if (year % 4 == 0 and year % 1_00 != 0) or (year % 4_00 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 _lowerCamelCase : str = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 _lowerCamelCase : Dict = day - 29 else: if day > days_per_month[month - 1]: month += 1 _lowerCamelCase : Union[str, Any] = day - days_per_month[month - 2] if month > 12: year += 1 _lowerCamelCase : Optional[int] = 1 if year < 20_01 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
83
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def snake_case_ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(F'''| 0 | 0 | {nor_gate(0, 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0, 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1, 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1, 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
83
1
"""simple docstring""" import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __snake_case : @staticmethod def SCREAMING_SNAKE_CASE ( *__lowerCAmelCase : List[str] , **__lowerCAmelCase : str ): """simple docstring""" pass @is_pipeline_test @require_vision class __snake_case ( unittest.TestCase): @require_torch def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , ) _lowerCamelCase : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _lowerCamelCase : List[Any] = image_classifier(__lowerCAmelCase , candidate_labels=['''a''', '''b''', '''c'''] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__lowerCAmelCase ) , [ [{'''score''': 0.3_33, '''label''': '''a'''}, {'''score''': 0.3_33, '''label''': '''b'''}, {'''score''': 0.3_33, '''label''': '''c'''}], [{'''score''': 0.3_33, '''label''': '''a'''}, {'''score''': 0.3_33, '''label''': '''c'''}, {'''score''': 0.3_33, '''label''': '''b'''}], ] , ) _lowerCamelCase : Optional[int] = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [ [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Optional[int] = pipeline( model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification''' , framework='''tf''' ) _lowerCamelCase : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _lowerCamelCase : List[str] = image_classifier(__lowerCAmelCase , candidate_labels=['''a''', '''b''', '''c'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [{'''score''': 0.3_33, '''label''': '''a'''}, {'''score''': 0.3_33, '''label''': '''b'''}, {'''score''': 0.3_33, '''label''': '''c'''}] , ) _lowerCamelCase : str = image_classifier([image] * 5 , candidate_labels=['''A''', '''B''', '''C'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [ [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], [ {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, {'''score''': 0.3_33, '''label''': ANY(__lowerCAmelCase )}, ], ] , ) @slow @require_torch def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , ) # This is an image of 2 cats with remotes and no planes _lowerCamelCase : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _lowerCamelCase : Union[str, Any] = image_classifier(__lowerCAmelCase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ] , ) _lowerCamelCase : Tuple = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [ [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ], ] * 5 , ) @slow @require_tf def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = pipeline( task='''zero-shot-image-classification''' , model='''openai/clip-vit-base-patch32''' , framework='''tf''' ) # This is an image of 2 cats with remotes and no planes _lowerCamelCase : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _lowerCamelCase : Dict = image_classifier(__lowerCAmelCase , candidate_labels=['''cat''', '''plane''', '''remote'''] ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ] , ) _lowerCamelCase : List[str] = image_classifier([image] * 5 , candidate_labels=['''cat''', '''plane''', '''remote'''] , batch_size=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase ) , [ [ {'''score''': 0.5_11, '''label''': '''remote'''}, {'''score''': 0.4_85, '''label''': '''cat'''}, {'''score''': 0.0_04, '''label''': '''plane'''}, ], ] * 5 , )
83
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : list[list[int]] ): '''simple docstring''' for i in range(1, len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(A_ ) ): for j in range(1, len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) lowerCAmelCase__ = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': 1000, '''block_out_channels''': [32, 64], '''attention_head_dim''': 8, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } lowerCAmelCase__ = { '''sample_size''': 64, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 3, '''num_class_embeds''': 1000, '''block_out_channels''': [192, 192 * 2, 192 * 3, 192 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } lowerCAmelCase__ = { '''sample_size''': 256, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': None, '''block_out_channels''': [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''default''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } lowerCAmelCase__ = { '''num_train_timesteps''': 40, '''sigma_min''': 0.0_0_2, '''sigma_max''': 8_0.0, } lowerCAmelCase__ = { '''num_train_timesteps''': 201, '''sigma_min''': 0.0_0_2, '''sigma_max''': 8_0.0, } lowerCAmelCase__ = { '''num_train_timesteps''': 151, '''sigma_min''': 0.0_0_2, '''sigma_max''': 8_0.0, } def snake_case_ ( A_ : List[str] ): '''simple docstring''' if isinstance(A_, A_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('''boolean value expected''' ) def snake_case_ ( A_ : Union[str, Any], A_ : Optional[Any], A_ : Tuple, A_ : Dict, A_ : Optional[Any]=False ): '''simple docstring''' _lowerCamelCase : Dict = checkpoint[F'''{old_prefix}.in_layers.0.weight'''] _lowerCamelCase : Union[str, Any] = checkpoint[F'''{old_prefix}.in_layers.0.bias'''] _lowerCamelCase : List[str] = checkpoint[F'''{old_prefix}.in_layers.2.weight'''] _lowerCamelCase : Any = checkpoint[F'''{old_prefix}.in_layers.2.bias'''] _lowerCamelCase : int = checkpoint[F'''{old_prefix}.emb_layers.1.weight'''] _lowerCamelCase : List[Any] = checkpoint[F'''{old_prefix}.emb_layers.1.bias'''] _lowerCamelCase : List[str] = checkpoint[F'''{old_prefix}.out_layers.0.weight'''] _lowerCamelCase : Union[str, Any] = checkpoint[F'''{old_prefix}.out_layers.0.bias'''] _lowerCamelCase : Tuple = checkpoint[F'''{old_prefix}.out_layers.3.weight'''] _lowerCamelCase : Optional[int] = checkpoint[F'''{old_prefix}.out_layers.3.bias'''] if has_skip: _lowerCamelCase : Any = checkpoint[F'''{old_prefix}.skip_connection.weight'''] _lowerCamelCase : str = checkpoint[F'''{old_prefix}.skip_connection.bias'''] return new_checkpoint def snake_case_ ( A_ : Optional[int], A_ : Tuple, A_ : Union[str, Any], A_ : Tuple, A_ : str=None ): '''simple docstring''' _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : str = checkpoint[F'''{old_prefix}.qkv.weight'''].chunk(3, dim=0 ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = checkpoint[F'''{old_prefix}.qkv.bias'''].chunk(3, dim=0 ) _lowerCamelCase : Tuple = checkpoint[F'''{old_prefix}.norm.weight'''] _lowerCamelCase : Union[str, Any] = checkpoint[F'''{old_prefix}.norm.bias'''] _lowerCamelCase : Tuple = weight_q.squeeze(-1 ).squeeze(-1 ) _lowerCamelCase : Optional[int] = bias_q.squeeze(-1 ).squeeze(-1 ) _lowerCamelCase : int = weight_k.squeeze(-1 ).squeeze(-1 ) _lowerCamelCase : int = bias_k.squeeze(-1 ).squeeze(-1 ) _lowerCamelCase : str = weight_v.squeeze(-1 ).squeeze(-1 ) _lowerCamelCase : int = bias_v.squeeze(-1 ).squeeze(-1 ) _lowerCamelCase : Optional[Any] = ( checkpoint[F'''{old_prefix}.proj_out.weight'''].squeeze(-1 ).squeeze(-1 ) ) _lowerCamelCase : List[Any] = checkpoint[F'''{old_prefix}.proj_out.bias'''].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def snake_case_ ( A_ : str, A_ : Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Optional[int] = torch.load(A_, map_location='''cpu''' ) _lowerCamelCase : List[str] = {} _lowerCamelCase : str = checkpoint['''time_embed.0.weight'''] _lowerCamelCase : Tuple = checkpoint['''time_embed.0.bias'''] _lowerCamelCase : str = checkpoint['''time_embed.2.weight'''] _lowerCamelCase : List[str] = checkpoint['''time_embed.2.bias'''] if unet_config["num_class_embeds"] is not None: _lowerCamelCase : List[str] = checkpoint['''label_emb.weight'''] _lowerCamelCase : Any = checkpoint['''input_blocks.0.0.weight'''] _lowerCamelCase : Dict = checkpoint['''input_blocks.0.0.bias'''] _lowerCamelCase : str = unet_config['''down_block_types'''] _lowerCamelCase : int = unet_config['''layers_per_block'''] _lowerCamelCase : Any = unet_config['''attention_head_dim'''] _lowerCamelCase : Optional[int] = unet_config['''block_out_channels'''] _lowerCamelCase : int = 1 _lowerCamelCase : List[Any] = channels_list[0] for i, layer_type in enumerate(A_ ): _lowerCamelCase : Tuple = channels_list[i] _lowerCamelCase : int = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(A_ ): _lowerCamelCase : Union[str, Any] = F'''down_blocks.{i}.resnets.{j}''' _lowerCamelCase : Optional[int] = F'''input_blocks.{current_layer}.0''' _lowerCamelCase : int = True if j == 0 and downsample_block_has_skip else False _lowerCamelCase : Optional[Any] = convert_resnet(A_, A_, A_, A_, has_skip=A_ ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(A_ ): _lowerCamelCase : Optional[Any] = F'''down_blocks.{i}.resnets.{j}''' _lowerCamelCase : int = F'''input_blocks.{current_layer}.0''' _lowerCamelCase : List[str] = True if j == 0 and downsample_block_has_skip else False _lowerCamelCase : Union[str, Any] = convert_resnet(A_, A_, A_, A_, has_skip=A_ ) _lowerCamelCase : Tuple = F'''down_blocks.{i}.attentions.{j}''' _lowerCamelCase : Any = F'''input_blocks.{current_layer}.1''' _lowerCamelCase : Optional[Any] = convert_attention( A_, A_, A_, A_, A_ ) current_layer += 1 if i != len(A_ ) - 1: _lowerCamelCase : Dict = F'''down_blocks.{i}.downsamplers.0''' _lowerCamelCase : Any = F'''input_blocks.{current_layer}.0''' _lowerCamelCase : List[Any] = convert_resnet(A_, A_, A_, A_ ) current_layer += 1 _lowerCamelCase : Tuple = current_channels # hardcoded the mid-block for now _lowerCamelCase : Union[str, Any] = '''mid_block.resnets.0''' _lowerCamelCase : Dict = '''middle_block.0''' _lowerCamelCase : Optional[Any] = convert_resnet(A_, A_, A_, A_ ) _lowerCamelCase : List[str] = '''mid_block.attentions.0''' _lowerCamelCase : Dict = '''middle_block.1''' _lowerCamelCase : Union[str, Any] = convert_attention(A_, A_, A_, A_, A_ ) _lowerCamelCase : Tuple = '''mid_block.resnets.1''' _lowerCamelCase : Optional[int] = '''middle_block.2''' _lowerCamelCase : Any = convert_resnet(A_, A_, A_, A_ ) _lowerCamelCase : str = 0 _lowerCamelCase : Any = unet_config['''up_block_types'''] for i, layer_type in enumerate(A_ ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): _lowerCamelCase : str = F'''up_blocks.{i}.resnets.{j}''' _lowerCamelCase : List[str] = F'''output_blocks.{current_layer}.0''' _lowerCamelCase : Union[str, Any] = convert_resnet(A_, A_, A_, A_, has_skip=A_ ) current_layer += 1 if i != len(A_ ) - 1: _lowerCamelCase : Optional[Any] = F'''up_blocks.{i}.upsamplers.0''' _lowerCamelCase : int = F'''output_blocks.{current_layer-1}.1''' _lowerCamelCase : str = convert_resnet(A_, A_, A_, A_ ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): _lowerCamelCase : Any = F'''up_blocks.{i}.resnets.{j}''' _lowerCamelCase : Optional[int] = F'''output_blocks.{current_layer}.0''' _lowerCamelCase : Optional[Any] = convert_resnet(A_, A_, A_, A_, has_skip=A_ ) _lowerCamelCase : str = F'''up_blocks.{i}.attentions.{j}''' _lowerCamelCase : Tuple = F'''output_blocks.{current_layer}.1''' _lowerCamelCase : int = convert_attention( A_, A_, A_, A_, A_ ) current_layer += 1 if i != len(A_ ) - 1: _lowerCamelCase : Any = F'''up_blocks.{i}.upsamplers.0''' _lowerCamelCase : Union[str, Any] = F'''output_blocks.{current_layer-1}.2''' _lowerCamelCase : List[str] = convert_resnet(A_, A_, A_, A_ ) _lowerCamelCase : str = checkpoint['''out.0.weight'''] _lowerCamelCase : Any = checkpoint['''out.0.bias'''] _lowerCamelCase : int = checkpoint['''out.2.weight'''] _lowerCamelCase : Optional[Any] = checkpoint['''out.2.bias'''] return new_checkpoint if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--unet_path''', default=None, type=str, required=True, help='''Path to the unet.pt to convert.''') parser.add_argument( '''--dump_path''', default=None, type=str, required=True, help='''Path to output the converted UNet model.''' ) parser.add_argument('''--class_cond''', default=True, type=str, help='''Whether the model is class-conditional.''') lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = strabool(args.class_cond) lowerCAmelCase__ = os.path.basename(args.unet_path) print(F"""Checkpoint: {ckpt_name}""") # Get U-Net config if "imagenet64" in ckpt_name: lowerCAmelCase__ = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): lowerCAmelCase__ = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: lowerCAmelCase__ = TEST_UNET_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") if not args.class_cond: lowerCAmelCase__ = None lowerCAmelCase__ = con_pt_to_diffuser(args.unet_path, unet_config) lowerCAmelCase__ = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: lowerCAmelCase__ = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: lowerCAmelCase__ = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): lowerCAmelCase__ = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") lowerCAmelCase__ = CMStochasticIterativeScheduler(**scheduler_config) lowerCAmelCase__ = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
83
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Optional[int] = data _lowerCamelCase : Node[T] | None = None def __str__( self : Optional[Any] ): """simple docstring""" return f'''{self.data}''' class __snake_case ( Generic[T]): def __init__( self : int ): """simple docstring""" _lowerCamelCase : Node[T] | None = None def __iter__( self : str ): """simple docstring""" _lowerCamelCase : List[str] = self.top while node: yield node.data _lowerCamelCase : Any = node.next def __str__( self : int ): """simple docstring""" return "->".join([str(__lowerCAmelCase ) for item in self] ) def __len__( self : int ): """simple docstring""" return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.top is None def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Tuple = Node(__lowerCAmelCase ) if not self.is_empty(): _lowerCamelCase : Optional[int] = self.top _lowerCamelCase : List[str] = node def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , __lowerCAmelCase ) _lowerCamelCase : Any = self.top _lowerCamelCase : Any = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = None if __name__ == "__main__": from doctest import testmod testmod()
83
1
"""simple docstring""" # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) lowerCAmelCase__ = '''pytorch_model.bin''' lowerCAmelCase__ = '''pytorch_model.bin.index.json''' lowerCAmelCase__ = '''adapter_config.json''' lowerCAmelCase__ = '''adapter_model.bin''' lowerCAmelCase__ = '''adapter_model.safetensors''' lowerCAmelCase__ = '''tf_model.h5''' lowerCAmelCase__ = '''tf_model.h5.index.json''' lowerCAmelCase__ = '''model.ckpt''' lowerCAmelCase__ = '''flax_model.msgpack''' lowerCAmelCase__ = '''flax_model.msgpack.index.json''' lowerCAmelCase__ = '''model.safetensors''' lowerCAmelCase__ = '''model.safetensors.index.json''' lowerCAmelCase__ = '''config.json''' lowerCAmelCase__ = '''preprocessor_config.json''' lowerCAmelCase__ = FEATURE_EXTRACTOR_NAME lowerCAmelCase__ = '''generation_config.json''' lowerCAmelCase__ = '''modelcard.json''' lowerCAmelCase__ = '''▁''' lowerCAmelCase__ = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility lowerCAmelCase__ = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. lowerCAmelCase__ = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] lowerCAmelCase__ = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def snake_case_ ( A_ : Dict ): '''simple docstring''' if version.parse(A_ ) < version.parse(A_ ): if "dev" in min_version: _lowerCamelCase : Optional[Any] = ( '''This example requires a source install from HuggingFace Transformers (see ''' '''`https://huggingface.co/docs/transformers/installation#install-from-source`),''' ) else: _lowerCamelCase : Union[str, Any] = F'''This example requires a minimum version of {min_version},''' error_message += F''' but the version found is {__version__}.\n''' raise ImportError( error_message + '''Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other ''' '''versions of HuggingFace Transformers.''' )
83
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase__ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCAmelCase__ = spec.loader.load_module() lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCAmelCase__ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = [] for config_class in list(CONFIG_MAPPING.values() ): _lowerCamelCase : Tuple = False # source code of `config_class` _lowerCamelCase : int = inspect.getsource(A_ ) _lowerCamelCase : str = _re_checkpoint.findall(A_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` _lowerCamelCase , _lowerCamelCase : Tuple = checkpoint # verify the checkpoint name corresponds to the checkpoint link _lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _lowerCamelCase : Union[str, Any] = True break _lowerCamelCase : Tuple = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
83
1
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __snake_case ( _lowercase , unittest.TestCase): snake_case__ : List[str] = CTRLTokenizer snake_case__ : List[str] = False snake_case__ : Any = False def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _lowerCamelCase : str = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] _lowerCamelCase : Dict = dict(zip(__lowerCAmelCase , range(len(__lowerCAmelCase ) ) ) ) _lowerCamelCase : Optional[Any] = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', ''''''] _lowerCamelCase : Any = {'''unk_token''': '''<unk>'''} _lowerCamelCase : Optional[int] = 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(__lowerCAmelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : str ): """simple docstring""" _lowerCamelCase : Dict = '''adapt react readapt apt''' _lowerCamelCase : Dict = '''adapt react readapt apt''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : str = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _lowerCamelCase : List[Any] = '''adapt react readapt apt''' _lowerCamelCase : Union[str, Any] = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() _lowerCamelCase : Union[str, Any] = tokenizer.tokenize(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = tokens + [tokenizer.unk_token] _lowerCamelCase : Any = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , __lowerCAmelCase )
83
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class __snake_case ( unittest.TestCase): pass @nightly @require_torch_gpu class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : int = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : str = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Dict = torch.manual_seed(0 ) _lowerCamelCase : List[Any] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : int = generator.manual_seed(0 ) _lowerCamelCase : List[str] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Optional[int] = torch.manual_seed(0 ) _lowerCamelCase : int = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images _lowerCamelCase : List[str] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Dict = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
83
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __snake_case ( _lowercase): def __init__( self : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : str ): """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM _lowerCamelCase : Union[str, Any] = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=__lowerCAmelCase , scheduler=__lowerCAmelCase ) @torch.no_grad() def __call__( self : Dict , __lowerCAmelCase : int = 1 , __lowerCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __lowerCAmelCase : float = 0.0 , __lowerCAmelCase : int = 5_0 , __lowerCAmelCase : Optional[bool] = None , __lowerCAmelCase : Optional[str] = "pil" , __lowerCAmelCase : bool = True , ): """simple docstring""" if isinstance(self.unet.config.sample_size , __lowerCAmelCase ): _lowerCamelCase : Tuple = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: _lowerCamelCase : List[Any] = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) and len(__lowerCAmelCase ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__lowerCAmelCase )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) _lowerCamelCase : Tuple = randn_tensor(__lowerCAmelCase , generator=__lowerCAmelCase , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__lowerCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _lowerCamelCase : Tuple = self.unet(__lowerCAmelCase , __lowerCAmelCase ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _lowerCamelCase : Union[str, Any] = self.scheduler.step( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , eta=__lowerCAmelCase , use_clipped_model_output=__lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample _lowerCamelCase : Dict = (image / 2 + 0.5).clamp(0 , 1 ) _lowerCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _lowerCamelCase : Tuple = self.numpy_to_pil(__lowerCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__lowerCAmelCase )
83
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = '''1''' lowerCAmelCase__ = '''0''' lowerCAmelCase__ = '''1''' lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('''Create inference session...''') lowerCAmelCase__ = ['''TensorrtExecutionProvider''', '''CUDAExecutionProvider'''] lowerCAmelCase__ = ort.InferenceSession('''model.onnx''', sess_options=sess_opt, providers=execution_provider) lowerCAmelCase__ = ort.RunOptions() lowerCAmelCase__ = 128 lowerCAmelCase__ = 1 lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) print('''Warm up phase...''') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Start inference...''') lowerCAmelCase__ = time.time() lowerCAmelCase__ = 2000 lowerCAmelCase__ = {} for iter in range(max_iters): lowerCAmelCase__ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Average Inference Time = {:.3f} ms'''.format((time.time() - start_time) * 1000 / max_iters))
83
1
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''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''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } lowerCAmelCase__ = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def snake_case_ ( A_ : List[str], A_ : str, A_ : Optional[int], A_ : Tuple, A_ : Dict ): '''simple docstring''' for attribute in key.split('''.''' ): _lowerCamelCase : Optional[Any] = getattr(A_, A_ ) if weight_type is not None: _lowerCamelCase : Dict = getattr(A_, A_ ).shape else: _lowerCamelCase : int = hf_pointer.shape assert hf_shape == value.shape, ( 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": _lowerCamelCase : str = value elif weight_type == "weight_g": _lowerCamelCase : Union[str, Any] = value elif weight_type == "weight_v": _lowerCamelCase : List[Any] = value elif weight_type == "bias": _lowerCamelCase : Optional[Any] = value else: _lowerCamelCase : Union[str, Any] = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def snake_case_ ( A_ : List[str], A_ : str ): '''simple docstring''' _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : Optional[int] = fairseq_model.state_dict() _lowerCamelCase : Tuple = hf_model.feature_extractor for name, value in fairseq_dict.items(): _lowerCamelCase : str = False if "conv_layers" in name: load_conv_layer( A_, A_, A_, A_, hf_model.config.feat_extract_norm == '''group''', ) _lowerCamelCase : List[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _lowerCamelCase : Tuple = True if "*" in mapped_key: _lowerCamelCase : int = name.split(A_ )[0].split('''.''' )[-2] _lowerCamelCase : List[str] = mapped_key.replace('''*''', A_ ) if "weight_g" in name: _lowerCamelCase : int = '''weight_g''' elif "weight_v" in name: _lowerCamelCase : List[Any] = '''weight_v''' elif "bias" in name and "relative_attention_bias" not in name: _lowerCamelCase : Dict = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj _lowerCamelCase : int = '''weight''' else: _lowerCamelCase : Tuple = 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 snake_case_ ( A_ : List[Any], A_ : int, A_ : Optional[int], A_ : int, A_ : Optional[Any] ): '''simple docstring''' _lowerCamelCase : Optional[Any] = full_name.split('''conv_layers.''' )[-1] _lowerCamelCase : str = name.split('''.''' ) _lowerCamelCase : str = int(items[0] ) _lowerCamelCase : Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) _lowerCamelCase : int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) _lowerCamelCase : List[Any] = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) _lowerCamelCase : Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) _lowerCamelCase : Optional[int] = 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 snake_case_ ( A_ : str, A_ : Any, A_ : Optional[int]=None ): '''simple docstring''' _lowerCamelCase : Any = torch.load(A_ ) _lowerCamelCase : Any = WavLMConfigOrig(checkpoint['''cfg'''] ) _lowerCamelCase : List[str] = WavLMOrig(A_ ) model.load_state_dict(checkpoint['''model'''] ) model.eval() if config_path is not None: _lowerCamelCase : Union[str, Any] = WavLMConfig.from_pretrained(A_ ) else: _lowerCamelCase : str = WavLMConfig() _lowerCamelCase : int = WavLMModel(A_ ) recursively_load_weights(A_, A_ ) hf_wavlm.save_pretrained(A_ ) if __name__ == "__main__": lowerCAmelCase__ = 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('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') lowerCAmelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
83
"""simple docstring""" import colorsys from PIL import Image # type: ignore def snake_case_ ( A_ : float, A_ : float, A_ : int ): '''simple docstring''' _lowerCamelCase : List[Any] = x _lowerCamelCase : List[Any] = y for step in range(A_ ): # noqa: B007 _lowerCamelCase : Dict = a * a - b * b + x _lowerCamelCase : List[str] = 2 * a * b + y _lowerCamelCase : Any = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(A_, 1, 1 ) ) def snake_case_ ( A_ : int = 8_00, A_ : int = 6_00, A_ : float = -0.6, A_ : float = 0, A_ : float = 3.2, A_ : int = 50, A_ : bool = True, ): '''simple docstring''' _lowerCamelCase : Tuple = Image.new('''RGB''', (image_width, image_height) ) _lowerCamelCase : int = img.load() # loop through the image-coordinates for image_x in range(A_ ): for image_y in range(A_ ): # determine the figure-coordinates based on the image-coordinates _lowerCamelCase : Optional[Any] = figure_width / image_width * image_height _lowerCamelCase : List[Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width _lowerCamelCase : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height _lowerCamelCase : str = get_distance(A_, A_, A_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: _lowerCamelCase : Dict = get_color_coded_rgb(A_ ) else: _lowerCamelCase : str = get_black_and_white_rgb(A_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCAmelCase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
83
1
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowerCAmelCase__ = random.Random() if is_torch_available(): import torch def snake_case_ ( A_ : Tuple, A_ : List[Any]=1.0, A_ : Optional[Any]=None, A_ : Optional[int]=None ): '''simple docstring''' if rng is None: _lowerCamelCase : Dict = global_rng _lowerCamelCase : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class __snake_case ( unittest.TestCase): def __init__( self : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any]=7 , __lowerCAmelCase : int=4_0_0 , __lowerCAmelCase : List[str]=2_0_0_0 , __lowerCAmelCase : str=1 , __lowerCAmelCase : Tuple=0.0 , __lowerCAmelCase : Dict=1_6_0_0_0 , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Any=True , ): """simple docstring""" _lowerCamelCase : int = parent _lowerCamelCase : Optional[Any] = batch_size _lowerCamelCase : int = min_seq_length _lowerCamelCase : Any = max_seq_length _lowerCamelCase : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _lowerCamelCase : Dict = feature_size _lowerCamelCase : int = padding_value _lowerCamelCase : Tuple = sampling_rate _lowerCamelCase : Optional[int] = return_attention_mask _lowerCamelCase : List[str] = do_normalize def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Any=False , __lowerCAmelCase : int=False ): """simple docstring""" def _flatten(__lowerCAmelCase : int ): return list(itertools.chain(*__lowerCAmelCase ) ) if equal_length: _lowerCamelCase : str = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size _lowerCamelCase : Optional[Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _lowerCamelCase : Dict = [np.asarray(__lowerCAmelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __snake_case ( _lowercase , unittest.TestCase): snake_case__ : List[str] = ASTFeatureExtractor def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = ASTFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _lowerCamelCase : List[str] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _lowerCamelCase : Tuple = [np.asarray(__lowerCAmelCase ) for speech_input in speech_inputs] # Test not batched input _lowerCamelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values _lowerCamelCase : Optional[int] = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # Test batched _lowerCamelCase : Optional[Any] = feat_extract(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_values _lowerCamelCase : Optional[Any] = feat_extract(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. _lowerCamelCase : str = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _lowerCamelCase : Any = np.asarray(__lowerCAmelCase ) _lowerCamelCase : Dict = feat_extract(__lowerCAmelCase , return_tensors='''np''' ).input_values _lowerCamelCase : List[Any] = feat_extract(__lowerCAmelCase , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) @require_torch def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" import torch _lowerCamelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _lowerCamelCase : Any = np.random.rand(1_0_0 ).astype(np.floataa ) _lowerCamelCase : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _lowerCamelCase : Union[str, Any] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) _lowerCamelCase : Tuple = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : List[str] ): """simple docstring""" from datasets import load_dataset _lowerCamelCase : str = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech _lowerCamelCase : int = ds.sort('''id''' ).select(range(__lowerCAmelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on _lowerCamelCase : Optional[Any] = self._load_datasamples(1 ) _lowerCamelCase : int = ASTFeatureExtractor() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , __lowerCAmelCase , atol=1E-4 ) )
83
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ): '''simple docstring''' _lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {} _lowerCamelCase : Union[str, Any] = padding_side return tokenizer( [line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, ) def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ): '''simple docstring''' _lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ): """simple docstring""" super().__init__() _lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' ) _lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' ) _lowerCamelCase : List[Any] = self.get_char_lens(self.src_file ) _lowerCamelCase : Optional[int] = max_source_length _lowerCamelCase : Optional[Any] = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _lowerCamelCase : List[Any] = tokenizer _lowerCamelCase : List[Any] = prefix if n_obs is not None: _lowerCamelCase : List[str] = self.src_lens[:n_obs] _lowerCamelCase : int = src_lang _lowerCamelCase : Union[str, Any] = tgt_lang def __len__( self : int ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = index + 1 # linecache starts at 1 _lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' ) _lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowerCAmelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _lowerCamelCase : Optional[int] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer ) _lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' ) _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' ) _lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze() _lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() _lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ): """simple docstring""" return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) _lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowerCAmelCase__ = getLogger(__name__) def snake_case_ ( A_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(A_ ) ) def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Dict = get_git_info() save_json(A_, os.path.join(A_, '''git_log.json''' ) ) def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ): '''simple docstring''' with open(A_, '''w''' ) as f: json.dump(A_, A_, indent=A_, **A_ ) def snake_case_ ( A_ : Any ): '''simple docstring''' with open(A_ ) as f: return json.load(A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ ) _lowerCamelCase : str = { '''repo_id''': str(A_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case_ ( A_ : Callable, A_ : Iterable ): '''simple docstring''' return list(map(A_, A_ ) ) def snake_case_ ( A_ : str, A_ : Tuple ): '''simple docstring''' with open(A_, '''wb''' ) as f: return pickle.dump(A_, A_ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' def remove_articles(A_ : str ): return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ ) def white_space_fix(A_ : Any ): return " ".join(text.split() ) def remove_punc(A_ : List[Any] ): _lowerCamelCase : Any = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case_ ( A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : str = normalize_answer(A_ ).split() _lowerCamelCase : int = normalize_answer(A_ ).split() _lowerCamelCase : str = Counter(A_ ) & Counter(A_ ) _lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 _lowerCamelCase : int = 1.0 * num_same / len(A_ ) _lowerCamelCase : str = 1.0 * num_same / len(A_ ) _lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case_ ( A_ : Dict, A_ : str ): '''simple docstring''' return normalize_answer(A_ ) == normalize_answer(A_ ) def snake_case_ ( A_ : List[str], A_ : List[str] ): '''simple docstring''' assert len(A_ ) == len(A_ ) _lowerCamelCase : Optional[Any] = 0 for hypo, pred in zip(A_, A_ ): em += exact_match_score(A_, A_ ) if len(A_ ) > 0: em /= len(A_ ) return {"em": em} def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Dict = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _lowerCamelCase : Tuple = '''dropout_rate''' for p in extra_params: if getattr(A_, A_, A_ ): if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) ) delattr(A_, A_ ) continue _lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p] setattr(A_, A_, getattr(A_, A_ ) ) delattr(A_, A_ ) return hparams, config
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfig''', '''JukeboxPriorConfig''', '''JukeboxVQVAEConfig''', ], '''tokenization_jukebox''': ['''JukeboxTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''JukeboxModel''', '''JukeboxPreTrainedModel''', '''JukeboxVQVAE''', '''JukeboxPrior''', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "camembert" def __init__( self : Optional[Any] , __lowerCAmelCase : Any=3_0_5_2_2 , __lowerCAmelCase : List[str]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Optional[int]=5_1_2 , __lowerCAmelCase : str=2 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : List[Any]=1E-12 , __lowerCAmelCase : Union[str, Any]=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : str="absolute" , __lowerCAmelCase : Any=True , __lowerCAmelCase : Optional[int]=None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Optional[Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : List[str] = classifier_dropout class __snake_case ( _lowercase): @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
83
1
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowerCAmelCase__ = 16 lowerCAmelCase__ = 32 def snake_case_ ( A_ : Accelerator, A_ : int = 16, A_ : str = "bert-base-cased" ): '''simple docstring''' _lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained(A_ ) _lowerCamelCase : Tuple = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(A_ : Dict ): # max_length=None => use the model max length (it's actually the default) _lowerCamelCase : str = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=A_, max_length=A_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset _lowerCamelCase : Any = datasets.map( A_, batched=A_, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=A_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowerCamelCase : List[Any] = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(A_ : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(A_, padding='''max_length''', max_length=1_28, return_tensors='''pt''' ) return tokenizer.pad(A_, padding='''longest''', return_tensors='''pt''' ) # Instantiate dataloaders. _lowerCamelCase : Optional[Any] = DataLoader( tokenized_datasets['''train'''], shuffle=A_, collate_fn=A_, batch_size=A_ ) _lowerCamelCase : int = DataLoader( tokenized_datasets['''validation'''], shuffle=A_, collate_fn=A_, batch_size=A_ ) return train_dataloader, eval_dataloader def snake_case_ ( A_ : List[str], A_ : str ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowerCamelCase : List[Any] = config['''lr'''] _lowerCamelCase : Union[str, Any] = int(config['''num_epochs'''] ) _lowerCamelCase : Optional[int] = int(config['''seed'''] ) _lowerCamelCase : Tuple = int(config['''batch_size'''] ) _lowerCamelCase : List[Any] = args.model_name_or_path set_seed(A_ ) _lowerCamelCase , _lowerCamelCase : List[str] = get_dataloaders(A_, A_, A_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowerCamelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(A_, return_dict=A_ ) # Instantiate optimizer _lowerCamelCase : Optional[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _lowerCamelCase : str = optimizer_cls(params=model.parameters(), lr=A_ ) if accelerator.state.deepspeed_plugin is not None: _lowerCamelCase : Any = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: _lowerCamelCase : Union[str, Any] = 1 _lowerCamelCase : Tuple = (len(A_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _lowerCamelCase : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=A_, num_warmup_steps=0, num_training_steps=A_, ) else: _lowerCamelCase : Tuple = DummyScheduler(A_, total_num_steps=A_, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Any = accelerator.prepare( A_, A_, A_, A_, A_ ) # We need to keep track of how many total steps we have iterated over _lowerCamelCase : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly _lowerCamelCase : Tuple = 0 # Now we train the model _lowerCamelCase : int = evaluate.load('''glue''', '''mrpc''' ) _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[str] = {} for epoch in range(A_, A_ ): model.train() for step, batch in enumerate(A_ ): _lowerCamelCase : Tuple = model(**A_ ) _lowerCamelCase : List[str] = outputs.loss _lowerCamelCase : Any = loss / gradient_accumulation_steps accelerator.backward(A_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() _lowerCamelCase : Any = 0 for step, batch in enumerate(A_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCamelCase : str = model(**A_ ) _lowerCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _lowerCamelCase , _lowerCamelCase : Tuple = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(A_ ) - 1: _lowerCamelCase : List[Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] _lowerCamelCase : Optional[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=A_, references=A_, ) _lowerCamelCase : Optional[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''', A_ ) _lowerCamelCase : Optional[Any] = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: _lowerCamelCase : Optional[int] = eval_metric['''accuracy'''] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, '''all_results.json''' ), '''w''' ) as f: json.dump(A_, A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Optional[Any] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''', type=A_, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=A_, ) parser.add_argument( '''--output_dir''', type=A_, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', ) parser.add_argument( '''--performance_lower_bound''', type=A_, default=A_, help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''', ) parser.add_argument( '''--num_epochs''', type=A_, default=3, help='''Number of train epochs.''', ) _lowerCamelCase : Tuple = parser.parse_args() _lowerCamelCase : str = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(A_, A_ ) if __name__ == "__main__": main()
83
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowerCAmelCase__ = '''<<<<<<< This should probably be modified because it mentions: ''' lowerCAmelCase__ = '''======= >>>>>>> ''' lowerCAmelCase__ = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] lowerCAmelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def snake_case_ ( A_ : Namespace ): '''simple docstring''' return ConvertCommand(args.tfds_path, args.datasets_directory ) class __snake_case ( _lowercase): @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : ArgumentParser ): """simple docstring""" _lowerCamelCase : List[str] = parser.add_parser( '''convert''' , help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.''' , ) train_parser.add_argument( '''--tfds_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.''' , ) train_parser.add_argument( '''--datasets_directory''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the HuggingFace Datasets folder.''' ) train_parser.set_defaults(func=__lowerCAmelCase ) def __init__( self : str , __lowerCAmelCase : str , __lowerCAmelCase : str , *__lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = get_logger('''datasets-cli/converting''' ) _lowerCamelCase : int = tfds_path _lowerCamelCase : Dict = datasets_directory def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if os.path.isdir(self._tfds_path ): _lowerCamelCase : Union[str, Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): _lowerCamelCase : Dict = os.path.dirname(self._tfds_path ) else: raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.''' ) _lowerCamelCase : int = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) _lowerCamelCase : str = [] _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Union[str, Any] = {} if os.path.isdir(self._tfds_path ): _lowerCamelCase : List[str] = os.listdir(__lowerCAmelCase ) else: _lowerCamelCase : Optional[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) _lowerCamelCase : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not os.path.isfile(__lowerCAmelCase ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('''Skipping file''' ) continue with open(__lowerCAmelCase , encoding='''utf-8''' ) as f: _lowerCamelCase : Tuple = f.readlines() _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Union[str, Any] = False _lowerCamelCase : int = False _lowerCamelCase : Tuple = [] for line in lines: _lowerCamelCase : Optional[int] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: _lowerCamelCase : Union[str, Any] = '''import datasets\n''' elif "import tensorflow" in out_line: # order is important here _lowerCamelCase : List[str] = '''''' continue elif "from absl import logging" in out_line: _lowerCamelCase : str = '''from datasets import logging\n''' elif "getLogger" in out_line: _lowerCamelCase : Union[str, Any] = out_line.replace('''getLogger''' , '''get_logger''' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): _lowerCamelCase : Dict = True _lowerCamelCase : Optional[int] = list(filter(lambda __lowerCAmelCase : e in out_line , __lowerCAmelCase ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(__lowerCAmelCase ) + '''\n''' ) out_lines.append(__lowerCAmelCase ) out_lines.append(__lowerCAmelCase ) continue else: for pattern, replacement in TO_CONVERT: _lowerCamelCase : str = re.sub(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: _lowerCamelCase : Dict = re.match(R'''from\stensorflow_datasets.*import\s([^\.\r\n]+)''' , __lowerCAmelCase ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(''',''' ) ) _lowerCamelCase : Union[str, Any] = '''from . import ''' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: _lowerCamelCase : Any = True out_lines.append(__lowerCAmelCase ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset _lowerCamelCase : Union[str, Any] = f_name.replace('''.py''' , '''''' ) _lowerCamelCase : List[str] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(__lowerCAmelCase ) if needs_manual_update: with_manual_update.append(__lowerCAmelCase ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.writelines(__lowerCAmelCase ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: _lowerCamelCase : Optional[int] = os.path.basename(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = imports_to_builder_map[f_name.replace('''.py''' , '''''' )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(__lowerCAmelCase , __lowerCAmelCase ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
83
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( _lowercase): snake_case__ : List[str] = "cvt" def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=3 , __lowerCAmelCase : List[str]=[7, 3, 3] , __lowerCAmelCase : int=[4, 2, 2] , __lowerCAmelCase : int=[2, 1, 1] , __lowerCAmelCase : str=[6_4, 1_9_2, 3_8_4] , __lowerCAmelCase : Dict=[1, 3, 6] , __lowerCAmelCase : Optional[Any]=[1, 2, 1_0] , __lowerCAmelCase : Dict=[4.0, 4.0, 4.0] , __lowerCAmelCase : Dict=[0.0, 0.0, 0.0] , __lowerCAmelCase : Union[str, Any]=[0.0, 0.0, 0.0] , __lowerCAmelCase : int=[0.0, 0.0, 0.1] , __lowerCAmelCase : Union[str, Any]=[True, True, True] , __lowerCAmelCase : str=[False, False, True] , __lowerCAmelCase : List[str]=["dw_bn", "dw_bn", "dw_bn"] , __lowerCAmelCase : List[Any]=[3, 3, 3] , __lowerCAmelCase : Dict=[1, 1, 1] , __lowerCAmelCase : str=[2, 2, 2] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Any=1E-12 , **__lowerCAmelCase : int , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : int = patch_sizes _lowerCamelCase : Optional[Any] = patch_stride _lowerCamelCase : str = patch_padding _lowerCamelCase : Any = embed_dim _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Dict = depth _lowerCamelCase : Optional[int] = mlp_ratio _lowerCamelCase : Any = attention_drop_rate _lowerCamelCase : Any = drop_rate _lowerCamelCase : Dict = drop_path_rate _lowerCamelCase : Optional[int] = qkv_bias _lowerCamelCase : int = cls_token _lowerCamelCase : int = qkv_projection_method _lowerCamelCase : Optional[Any] = kernel_qkv _lowerCamelCase : List[str] = padding_kv _lowerCamelCase : Tuple = stride_kv _lowerCamelCase : Union[str, Any] = padding_q _lowerCamelCase : Optional[Any] = stride_q _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps
83
"""simple docstring""" def snake_case_ ( A_ : list, A_ : list, A_ : int, A_ : int, A_ : int ): '''simple docstring''' if index == number_of_items: return 0 _lowerCamelCase : int = 0 _lowerCamelCase : str = 0 _lowerCamelCase : Dict = knapsack(A_, A_, A_, A_, index + 1 ) if weights[index] <= max_weight: _lowerCamelCase : Tuple = values[index] + knapsack( A_, A_, A_, max_weight - weights[index], index + 1 ) return max(A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class __snake_case : def __init__( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = '''''' _lowerCamelCase : str = '''''' _lowerCamelCase : Any = [] _lowerCamelCase : Optional[Any] = 0 _lowerCamelCase : Tuple = 2_5_6 _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : str = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Dict = 0 def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : List[Any] = cva.imread(__lowerCAmelCase , 0 ) _lowerCamelCase : Tuple = copy.deepcopy(self.img ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = plt.hist(self.img.ravel() , 2_5_6 , [0, 2_5_6] , label='''x''' ) _lowerCamelCase : Dict = np.sum(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): _lowerCamelCase : Tuple = x[i] / self.k self.sk += prk _lowerCamelCase : str = (self.L - 1) * self.sk if self.rem != 0: _lowerCamelCase : List[Any] = int(last % last ) _lowerCamelCase : Optional[Any] = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = int(np.ma.count(self.img ) / self.img[1].size ) _lowerCamelCase : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): _lowerCamelCase : int = self.img[j][i] if num != self.last_list[num]: _lowerCamelCase : Optional[int] = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" plt.hist(self.img.ravel() , 2_5_6 , [0, 2_5_6] ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(5_0_0_0 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase__ = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') lowerCAmelCase__ = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
83
"""simple docstring""" from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=_lowercase): snake_case__ : Optional[Any] = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : List[Any] ): """simple docstring""" requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , *__lowerCAmelCase : str , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : int , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
83
1
"""simple docstring""" import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) lowerCAmelCase__ = logging.getLogger(__name__) @dataclass(frozen=_lowercase) class __snake_case : snake_case__ : str snake_case__ : str snake_case__ : Optional[str] = None snake_case__ : Optional[str] = None snake_case__ : Optional[str] = None @dataclass(frozen=_lowercase) class __snake_case : snake_case__ : List[int] snake_case__ : Optional[List[int]] = None snake_case__ : Optional[List[int]] = None snake_case__ : Optional[Union[int, float]] = None snake_case__ : Optional[int] = None if is_torch_available(): import torch from torch.utils.data import Dataset class __snake_case ( _lowercase): snake_case__ : List[InputFeatures] def __init__( self : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : PreTrainedTokenizer , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : bool = False , ): """simple docstring""" _lowerCamelCase : List[str] = hans_processors[task]() _lowerCamelCase : Optional[int] = os.path.join( __lowerCAmelCase , '''cached_{}_{}_{}_{}'''.format( '''dev''' if evaluate else '''train''' , tokenizer.__class__.__name__ , str(__lowerCAmelCase ) , __lowerCAmelCase , ) , ) _lowerCamelCase : int = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) _lowerCamelCase , _lowerCamelCase : List[Any] = label_list[2], label_list[1] _lowerCamelCase : Tuple = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _lowerCamelCase : List[Any] = cached_features_file + '''.lock''' with FileLock(__lowerCAmelCase ): if os.path.exists(__lowerCAmelCase ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) _lowerCamelCase : Optional[int] = torch.load(__lowerCAmelCase ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) _lowerCamelCase : Optional[int] = ( processor.get_dev_examples(__lowerCAmelCase ) if evaluate else processor.get_train_examples(__lowerCAmelCase ) ) logger.info('''Training examples: %s''' , len(__lowerCAmelCase ) ) _lowerCamelCase : Optional[Any] = hans_convert_examples_to_features(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) logger.info('''Saving features into cached file %s''' , __lowerCAmelCase ) torch.save(self.features , __lowerCAmelCase ) def __len__( self : Any ): """simple docstring""" return len(self.features ) def __getitem__( self : int , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" return self.features[i] def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.label_list if is_tf_available(): import tensorflow as tf class __snake_case : snake_case__ : List[InputFeatures] def __init__( self : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : PreTrainedTokenizer , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] = 1_2_8 , __lowerCAmelCase : str=False , __lowerCAmelCase : bool = False , ): """simple docstring""" _lowerCamelCase : Union[str, Any] = hans_processors[task]() _lowerCamelCase : Optional[int] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) _lowerCamelCase , _lowerCamelCase : List[str] = label_list[2], label_list[1] _lowerCamelCase : Optional[Any] = label_list _lowerCamelCase : List[Any] = processor.get_dev_examples(__lowerCAmelCase ) if evaluate else processor.get_train_examples(__lowerCAmelCase ) _lowerCamelCase : int = hans_convert_examples_to_features(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc='''convert examples to features''' ): if ex_index % 1_0_0_0_0 == 0: logger.info('''Writing example %d of %d''' % (ex_index, len(__lowerCAmelCase )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) _lowerCamelCase : Union[str, Any] = tf.data.Dataset.from_generator( __lowerCAmelCase , ( { '''example_id''': tf.intaa, '''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa, }, tf.intaa, ) , ( { '''example_id''': tf.TensorShape([] ), '''input_ids''': tf.TensorShape([None, None] ), '''attention_mask''': tf.TensorShape([None, None] ), '''token_type_ids''': tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.dataset def __len__( self : List[str] ): """simple docstring""" return len(self.features ) def __getitem__( self : List[Any] , __lowerCAmelCase : List[str] ): """simple docstring""" return self.features[i] def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.label_list class __snake_case ( _lowercase): def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(__lowerCAmelCase , '''heuristics_train_set.txt''' ) ) , '''train''' ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Dict ): """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(__lowerCAmelCase , '''heuristics_evaluation_set.txt''' ) ) , '''dev''' ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return ["contradiction", "entailment", "neutral"] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [] for i, line in enumerate(__lowerCAmelCase ): if i == 0: continue _lowerCamelCase : str = '''%s-%s''' % (set_type, line[0]) _lowerCamelCase : List[str] = line[5] _lowerCamelCase : List[str] = line[6] _lowerCamelCase : Optional[Any] = line[7][2:] if line[7].startswith('''ex''' ) else line[7] _lowerCamelCase : Union[str, Any] = line[0] examples.append(InputExample(guid=__lowerCAmelCase , text_a=__lowerCAmelCase , text_b=__lowerCAmelCase , label=__lowerCAmelCase , pairID=__lowerCAmelCase ) ) return examples def snake_case_ ( A_ : List[InputExample], A_ : List[str], A_ : int, A_ : PreTrainedTokenizer, ): '''simple docstring''' _lowerCamelCase : str = {label: i for i, label in enumerate(A_ )} _lowerCamelCase : Dict = [] for ex_index, example in tqdm.tqdm(enumerate(A_ ), desc='''convert examples to features''' ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d''' % (ex_index) ) _lowerCamelCase : Tuple = tokenizer( example.text_a, example.text_b, add_special_tokens=A_, max_length=A_, padding='''max_length''', truncation=A_, return_overflowing_tokens=A_, ) _lowerCamelCase : str = label_map[example.label] if example.label in label_map else 0 _lowerCamelCase : Dict = int(example.pairID ) features.append(InputFeatures(**A_, label=A_, pairID=A_ ) ) for i, example in enumerate(examples[:5] ): logger.info('''*** Example ***''' ) logger.info(F'''guid: {example}''' ) logger.info(F'''features: {features[i]}''' ) return features lowerCAmelCase__ = { '''hans''': 3, } lowerCAmelCase__ = { '''hans''': HansProcessor, }
83
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __snake_case ( unittest.TestCase): @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Union[str, Any] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids _lowerCamelCase : Optional[int] = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids _lowerCamelCase : List[Any] = shift_tokens_right(__lowerCAmelCase , model.config.pad_token_id , model.config.decoder_start_token_id ) _lowerCamelCase : int = model(__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase ).logits _lowerCamelCase : Optional[Any] = optax.softmax_cross_entropy(__lowerCAmelCase , onehot(__lowerCAmelCase , logits.shape[-1] ) ).mean() _lowerCamelCase : Dict = -(labels.shape[-1] * loss.item()) _lowerCamelCase : Dict = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
83
1
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase__ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCAmelCase__ = spec.loader.load_module() lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCAmelCase__ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = [] for config_class in list(CONFIG_MAPPING.values() ): _lowerCamelCase : Tuple = False # source code of `config_class` _lowerCamelCase : int = inspect.getsource(A_ ) _lowerCamelCase : str = _re_checkpoint.findall(A_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` _lowerCamelCase , _lowerCamelCase : Tuple = checkpoint # verify the checkpoint name corresponds to the checkpoint link _lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _lowerCamelCase : Union[str, Any] = True break _lowerCamelCase : Tuple = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
83
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''', [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ], ) def snake_case_ ( A_ : Dict, A_ : List[str] ): '''simple docstring''' _lowerCamelCase : int = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''', '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) _lowerCamelCase : str = DatasetInfosDict.from_directory(A_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''', [ DatasetInfo(), DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ), ], ) def snake_case_ ( A_ : str, A_ : DatasetInfo ): '''simple docstring''' _lowerCamelCase : Optional[Any] = str(A_ ) dataset_info.write_to_directory(A_ ) _lowerCamelCase : str = DatasetInfo.from_directory(A_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(A_, '''dataset_info.json''' ) ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = DatasetInfo( description='''foo''', citation='''bar''', homepage='''https://foo.bar''', license='''CC0''', features=Features({'''a''': Value('''int32''' )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train''', '''num_examples''': 42}], download_checksums={}, download_size=13_37, post_processing_size=4_42, dataset_size=12_34, size_in_bytes=13_37 + 4_42 + 12_34, ) _lowerCamelCase : Optional[Any] = dataset_info._to_yaml_dict() assert sorted(A_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) ) _lowerCamelCase : str = yaml.safe_dump(A_ ) _lowerCamelCase : Tuple = yaml.safe_load(A_ ) assert dataset_info_yaml_dict == reloaded def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : int = DatasetInfo() _lowerCamelCase : Dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''', [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=13_37 ), } ), ], ) def snake_case_ ( A_ : Optional[Any], A_ : DatasetInfosDict ): '''simple docstring''' _lowerCamelCase : List[str] = str(A_ ) dataset_infos_dict.write_to_directory(A_ ) _lowerCamelCase : List[Any] = DatasetInfosDict.from_directory(A_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _lowerCamelCase : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _lowerCamelCase : Any = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(A_, '''README.md''' ) )
83
1
"""simple docstring""" from pathlib import Path import fire def snake_case_ ( A_ : str, A_ : str, A_ : int ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = Path(A_ ) _lowerCamelCase : int = Path(A_ ) dest_dir.mkdir(exist_ok=A_ ) for path in src_dir.iterdir(): _lowerCamelCase : Optional[Any] = [x.rstrip() for x in list(path.open().readlines() )][:n] _lowerCamelCase : Any = dest_dir.joinpath(path.name ) print(A_ ) dest_path.open('''w''' ).write('''\n'''.join(A_ ) ) if __name__ == "__main__": fire.Fire(minify)
83
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __snake_case : def __init__( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : List[str]=2_4 , __lowerCAmelCase : str=1_6 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : int=4 , __lowerCAmelCase : int=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : List[Any]=0.02 , __lowerCAmelCase : str=None , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Union[str, Any]=2 , ): """simple docstring""" _lowerCamelCase : List[str] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : Tuple = patch_size _lowerCamelCase : Optional[int] = max_length _lowerCamelCase : List[Any] = num_mel_bins _lowerCamelCase : int = is_training _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : Dict = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : List[str] = scope _lowerCamelCase : Optional[int] = frequency_stride _lowerCamelCase : List[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowerCamelCase : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _lowerCamelCase : Union[str, Any] = (self.max_length - self.patch_size) // self.time_stride + 1 _lowerCamelCase : Any = frequency_out_dimension * time_out_dimension _lowerCamelCase : List[Any] = num_patches + 2 def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Optional[int] = self.get_config() return config, input_values, labels def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = ASTModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Optional[Any] = config_and_inputs _lowerCamelCase : int = {'''input_values''': input_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Any = False snake_case__ : List[Any] = False snake_case__ : Optional[Any] = False snake_case__ : Optional[Any] = False def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[int] = ASTModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCamelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : str = ['''input_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Union[str, Any] = ASTModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' ) _lowerCamelCase , _lowerCamelCase : str = torchaudio.load(A_ ) return audio, sampling_rate @require_torch @require_torchaudio class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.default_feature_extractor _lowerCamelCase : Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = self.default_feature_extractor _lowerCamelCase , _lowerCamelCase : List[Any] = prepare_audio() _lowerCamelCase : Dict = audio.squeeze().numpy() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , sampling_rate=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Tuple = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : Tuple = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
83
1
"""simple docstring""" lowerCAmelCase__ = [ (1000, '''M'''), (900, '''CM'''), (500, '''D'''), (400, '''CD'''), (100, '''C'''), (90, '''XC'''), (50, '''L'''), (40, '''XL'''), (10, '''X'''), (9, '''IX'''), (5, '''V'''), (4, '''IV'''), (1, '''I'''), ] def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 1_00, '''D''': 5_00, '''M''': 10_00} _lowerCamelCase : List[Any] = 0 _lowerCamelCase : int = 0 while place < len(A_ ): if (place + 1 < len(A_ )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : str = [] for arabic, roman in ROMAN: ((_lowerCamelCase) , (_lowerCamelCase)) : int = divmod(A_, A_ ) result.append(roman * factor ) if number == 0: break return "".join(A_ ) if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( A_ : Dict, A_ : bool = True, A_ : float = math.inf, A_ : float = -math.inf, A_ : float = math.inf, A_ : float = -math.inf, A_ : bool = False, A_ : float = 1_00, A_ : float = 0.01, A_ : float = 1, ): '''simple docstring''' _lowerCamelCase : Optional[int] = False _lowerCamelCase : str = search_prob _lowerCamelCase : str = start_temperate _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : int = 0 _lowerCamelCase : Any = None while not search_end: _lowerCamelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCamelCase : Tuple = current_state scores.append(A_ ) iterations += 1 _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCamelCase : List[Any] = random.randint(0, len(A_ ) - 1 ) # picking a random neighbor _lowerCamelCase : Dict = neighbors.pop(A_ ) _lowerCamelCase : Union[str, Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCamelCase : Optional[Any] = picked_neighbor else: _lowerCamelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCamelCase : Union[str, Any] = picked_neighbor _lowerCamelCase : List[str] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCamelCase : Tuple = True else: _lowerCamelCase : Optional[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A_ ), A_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def snake_case_ ( A_ : Optional[int], A_ : List[Any] ): '''simple docstring''' return (3 * x**2) - (6 * y) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
83
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowerCAmelCase__ = logging.get_logger(__name__) class __snake_case ( _lowercase): def __init__( self : Dict , *__lowerCAmelCase : List[Any] , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" warnings.warn( '''The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use ChineseCLIPImageProcessor instead.''' , __lowerCAmelCase , ) super().__init__(*__lowerCAmelCase , **__lowerCAmelCase )
83
"""simple docstring""" from collections import namedtuple lowerCAmelCase__ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase__ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def snake_case_ ( A_ : float, A_ : str, A_ : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ''', '''.join(A_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ''', '''.join(A_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput lowerCAmelCase__ = '''scheduler_config.json''' class __snake_case ( _lowercase): snake_case__ : List[Any] = 1 snake_case__ : Tuple = 2 snake_case__ : Union[str, Any] = 3 snake_case__ : Any = 4 snake_case__ : Any = 5 snake_case__ : Union[str, Any] = 6 snake_case__ : Optional[Any] = 7 snake_case__ : Optional[int] = 8 snake_case__ : Any = 9 snake_case__ : List[str] = 1_0 snake_case__ : int = 1_1 snake_case__ : Tuple = 1_2 snake_case__ : Optional[Any] = 1_3 snake_case__ : Union[str, Any] = 1_4 @dataclass class __snake_case ( _lowercase): snake_case__ : torch.FloatTensor class __snake_case : snake_case__ : str = SCHEDULER_CONFIG_NAME snake_case__ : List[Any] = [] snake_case__ : List[str] = True @classmethod def SCREAMING_SNAKE_CASE ( cls : Tuple , __lowerCAmelCase : Dict[str, Any] = None , __lowerCAmelCase : Optional[str] = None , __lowerCAmelCase : Optional[int]=False , **__lowerCAmelCase : str , ): """simple docstring""" _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = cls.load_config( pretrained_model_name_or_path=__lowerCAmelCase , subfolder=__lowerCAmelCase , return_unused_kwargs=__lowerCAmelCase , return_commit_hash=__lowerCAmelCase , **__lowerCAmelCase , ) return cls.from_config(__lowerCAmelCase , return_unused_kwargs=__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Union[str, os.PathLike] , __lowerCAmelCase : bool = False , **__lowerCAmelCase : Optional[int] ): """simple docstring""" self.save_config(save_directory=__lowerCAmelCase , push_to_hub=__lowerCAmelCase , **__lowerCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self._get_compatibles() @classmethod def SCREAMING_SNAKE_CASE ( cls : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = list(set([cls.__name__] + cls._compatibles ) ) _lowerCamelCase : Dict = importlib.import_module(__name__.split('''.''' )[0] ) _lowerCamelCase : Tuple = [ getattr(__lowerCAmelCase , __lowerCAmelCase ) for c in compatible_classes_str if hasattr(__lowerCAmelCase , __lowerCAmelCase ) ] return compatible_classes
83
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case ( _lowercase): def __init__( self : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=9_9 , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : Optional[int]=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : int=5_1_2 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any="None" , __lowerCAmelCase : str=3 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[Any]=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Dict = use_input_mask _lowerCamelCase : Tuple = use_token_type_ids _lowerCamelCase : Optional[Any] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Optional[int] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : int = relative_attention _lowerCamelCase : Union[str, Any] = position_biased_input _lowerCamelCase : str = pos_att_type _lowerCamelCase : Tuple = scope def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : int = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : str = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : List[Any] = model(__lowerCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : Dict = DebertaVaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : Tuple = DebertaVaForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = DebertaVaForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : int = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True snake_case__ : List[Any] = False snake_case__ : int = False snake_case__ : Optional[Any] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) _lowerCamelCase : List[str] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] # compare the actual values for a slice. _lowerCamelCase : Union[str, Any] = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
83
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 subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file lowerCAmelCase__ = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def snake_case_ ( A_ : Union[str, Any]=None ): '''simple docstring''' if subparsers is not None: _lowerCamelCase : Optional[Any] = subparsers.add_parser('''tpu-config''', description=_description ) else: _lowerCamelCase : Any = argparse.ArgumentParser('''Accelerate tpu-config command''', description=_description ) # Core arguments _lowerCamelCase : Optional[int] = parser.add_argument_group( '''Config Arguments''', '''Arguments that can be configured through `accelerate config`.''' ) config_args.add_argument( '''--config_file''', type=A_, default=A_, help='''Path to the config file to use for accelerate.''', ) config_args.add_argument( '''--tpu_name''', default=A_, help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''', ) config_args.add_argument( '''--tpu_zone''', default=A_, help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''', ) _lowerCamelCase : Optional[Any] = parser.add_argument_group('''TPU Arguments''', '''Arguments for options ran inside the TPU.''' ) pod_args.add_argument( '''--use_alpha''', action='''store_true''', help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''', ) pod_args.add_argument( '''--command_file''', default=A_, help='''The path to the file containing the commands to run on the pod on startup.''', ) pod_args.add_argument( '''--command''', action='''append''', nargs='''+''', help='''A command to run on the pod. Can be passed multiple times.''', ) pod_args.add_argument( '''--install_accelerate''', action='''store_true''', help='''Whether to install accelerate on the pod. Defaults to False.''', ) pod_args.add_argument( '''--accelerate_version''', default='''latest''', help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''', ) pod_args.add_argument( '''--debug''', action='''store_true''', help='''If set, will print the command that would be run instead of running it.''' ) if subparsers is not None: parser.set_defaults(func=A_ ) return parser def snake_case_ ( A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Optional[Any] = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(A_ ): _lowerCamelCase : int = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: _lowerCamelCase : List[Any] = defaults.command_file if not args.command and defaults.commands is not None: _lowerCamelCase : int = defaults.commands if not args.tpu_name: _lowerCamelCase : List[Any] = defaults.tpu_name if not args.tpu_zone: _lowerCamelCase : Optional[int] = defaults.tpu_zone if args.accelerate_version == "dev": _lowerCamelCase : Any = '''git+https://github.com/huggingface/accelerate.git''' elif args.accelerate_version == "latest": _lowerCamelCase : Optional[int] = '''accelerate -U''' elif isinstance(parse(args.accelerate_version ), A_ ): _lowerCamelCase : Optional[int] = F'''accelerate=={args.accelerate_version}''' if not args.command_file and not args.command: raise ValueError('''You must specify either a command file or a command to run on the pod.''' ) if args.command_file: with open(args.command_file, '''r''' ) as f: _lowerCamelCase : Optional[Any] = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0], A_ ): _lowerCamelCase : Union[str, Any] = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate _lowerCamelCase : Optional[int] = ['''cd /usr/share'''] if args.install_accelerate: new_cmd += [F'''pip install {args.accelerate_version}'''] new_cmd += args.command _lowerCamelCase : List[Any] = '''; '''.join(A_ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess _lowerCamelCase : Optional[int] = ['''gcloud'''] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'''Running {" ".join(A_ )}''' ) return subprocess.run(A_ ) print('''Successfully setup pod.''' ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = tpu_command_parser() _lowerCamelCase : Union[str, Any] = parser.parse_args() tpu_command_launcher(A_ )
83
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = '''hf-internal-testing/tiny-random-bert''' lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''') lowerCAmelCase__ = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6''' class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = cached_file(__lowerCAmelCase , __lowerCAmelCase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__lowerCAmelCase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : Optional[int] = f.read() self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) self.assertTrue(os.path.isfile(__lowerCAmelCase ) ) # File is cached at the same place the second time. _lowerCamelCase : Tuple = cached_file(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Using a specific revision to test the full commit hash. _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''9b8c223''' ) self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): _lowerCamelCase : Optional[int] = cached_file('''tiny-random-bert''' , __lowerCAmelCase ) with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): _lowerCamelCase : str = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''aaaa''' ) with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : int = cached_file(__lowerCAmelCase , '''conf''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , '''conf''' ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : List[Any] = f.read() self.assertTrue(os.path.isfile(os.path.join(__lowerCAmelCase , '''.no_exist''' , __lowerCAmelCase , '''conf''' ) ) ) _lowerCamelCase : str = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = cached_file(__lowerCAmelCase , '''conf''' , local_files_only=__lowerCAmelCase , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Any = mock.Mock() _lowerCamelCase : Optional[Any] = 5_0_0 _lowerCamelCase : Dict = {} _lowerCamelCase : List[Any] = HTTPError _lowerCamelCase : int = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__lowerCAmelCase ) as mock_head: _lowerCamelCase : Union[str, Any] = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_connection_errors=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __lowerCAmelCase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase , revision='''ahaha''' ) _lowerCamelCase : Dict = get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase ) # The name is the cached name which is not very easy to test, so instead we load the content. _lowerCamelCase : Dict = json.loads(open(__lowerCAmelCase , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = Path(__lowerCAmelCase ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__lowerCAmelCase , '''a.txt''' ) , str(__lowerCAmelCase ) ) self.assertIsNone(get_file_from_repo(__lowerCAmelCase , '''b.txt''' ) )
83
1
"""simple docstring""" from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowerCAmelCase__ = logging.get_logger(__name__) class __snake_case ( _lowercase): snake_case__ : Dict = ["audio_values", "audio_mask"] def __init__( self : List[str] , __lowerCAmelCase : Optional[Any]=2_0_4_8 , __lowerCAmelCase : Optional[int]=1 , __lowerCAmelCase : Dict=[1_6, 1_6] , __lowerCAmelCase : Optional[Any]=1_2_8 , __lowerCAmelCase : Optional[int]=4_4_1_0_0 , __lowerCAmelCase : Optional[Any]=8_6 , __lowerCAmelCase : Dict=2_0_4_8 , __lowerCAmelCase : Tuple=0.0 , **__lowerCAmelCase : Dict , ): """simple docstring""" super().__init__( feature_size=__lowerCAmelCase , sampling_rate=__lowerCAmelCase , padding_value=__lowerCAmelCase , **__lowerCAmelCase , ) _lowerCamelCase : str = spectrogram_length _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = patch_size _lowerCamelCase : Optional[Any] = feature_size // self.patch_size[1] _lowerCamelCase : Any = n_fft _lowerCamelCase : int = sampling_rate // hop_length_to_sampling_rate _lowerCamelCase : Optional[int] = sampling_rate _lowerCamelCase : Optional[Any] = padding_value _lowerCamelCase : str = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=__lowerCAmelCase , min_frequency=0.0 , max_frequency=2_20_50.0 , sampling_rate=__lowerCAmelCase , norm='''slaney''' , mel_scale='''slaney''' , ).T def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : np.array ): """simple docstring""" _lowerCamelCase : Tuple = spectrogram( __lowerCAmelCase , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='''dB''' , db_range=80.0 , ) _lowerCamelCase : Union[str, Any] = log_spec[:, :-1] _lowerCamelCase : Optional[Any] = log_spec - 20.0 _lowerCamelCase : List[Any] = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self : Optional[Any] , __lowerCAmelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __lowerCAmelCase : Optional[Union[str, TensorType]] = None , __lowerCAmelCase : Optional[bool] = True , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , **__lowerCAmelCase : List[str] , ): """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( '''This feature extractor is set to support sampling rate''' f''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled''' f''' with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) _lowerCamelCase : Union[str, Any] = isinstance(__lowerCAmelCase , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) _lowerCamelCase : List[str] = is_batched_numpy or ( isinstance(__lowerCAmelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _lowerCamelCase : str = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(__lowerCAmelCase , np.ndarray ): _lowerCamelCase : Any = np.asarray(__lowerCAmelCase , dtype=np.floataa ) elif isinstance(__lowerCAmelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _lowerCamelCase : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _lowerCamelCase : Tuple = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis _lowerCamelCase : int = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , __lowerCAmelCase ): _lowerCamelCase : Union[str, Any] = [np.asarray(__lowerCAmelCase , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask _lowerCamelCase : List[Any] = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: _lowerCamelCase : Any = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] _lowerCamelCase : str = np.array(__lowerCAmelCase ).astype(np.floataa ) # convert into correct format for padding _lowerCamelCase : List[str] = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch _lowerCamelCase : Optional[int] = np.ones([len(__lowerCAmelCase ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) _lowerCamelCase : int = padded_audio_features * self.padding_value for i in range(len(__lowerCAmelCase ) ): _lowerCamelCase : List[str] = audio_features[i] _lowerCamelCase : Optional[Any] = feature # return as BatchFeature if return_attention_mask: _lowerCamelCase : Union[str, Any] = {'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask} else: _lowerCamelCase : Any = {'''audio_values''': padded_audio_features} _lowerCamelCase : Optional[int] = BatchFeature(data=__lowerCAmelCase , tensor_type=__lowerCAmelCase ) return encoded_inputs
83
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( _lowercase): snake_case__ : List[str] = "cvt" def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=3 , __lowerCAmelCase : List[str]=[7, 3, 3] , __lowerCAmelCase : int=[4, 2, 2] , __lowerCAmelCase : int=[2, 1, 1] , __lowerCAmelCase : str=[6_4, 1_9_2, 3_8_4] , __lowerCAmelCase : Dict=[1, 3, 6] , __lowerCAmelCase : Optional[Any]=[1, 2, 1_0] , __lowerCAmelCase : Dict=[4.0, 4.0, 4.0] , __lowerCAmelCase : Dict=[0.0, 0.0, 0.0] , __lowerCAmelCase : Union[str, Any]=[0.0, 0.0, 0.0] , __lowerCAmelCase : int=[0.0, 0.0, 0.1] , __lowerCAmelCase : Union[str, Any]=[True, True, True] , __lowerCAmelCase : str=[False, False, True] , __lowerCAmelCase : List[str]=["dw_bn", "dw_bn", "dw_bn"] , __lowerCAmelCase : List[Any]=[3, 3, 3] , __lowerCAmelCase : Dict=[1, 1, 1] , __lowerCAmelCase : str=[2, 2, 2] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Any=1E-12 , **__lowerCAmelCase : int , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : int = patch_sizes _lowerCamelCase : Optional[Any] = patch_stride _lowerCamelCase : str = patch_padding _lowerCamelCase : Any = embed_dim _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Dict = depth _lowerCamelCase : Optional[int] = mlp_ratio _lowerCamelCase : Any = attention_drop_rate _lowerCamelCase : Any = drop_rate _lowerCamelCase : Dict = drop_path_rate _lowerCamelCase : Optional[int] = qkv_bias _lowerCamelCase : int = cls_token _lowerCamelCase : int = qkv_projection_method _lowerCamelCase : Optional[Any] = kernel_qkv _lowerCamelCase : List[str] = padding_kv _lowerCamelCase : Tuple = stride_kv _lowerCamelCase : Union[str, Any] = padding_q _lowerCamelCase : Optional[Any] = stride_q _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps
83
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = {'''configuration_mbart''': ['''MBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MBartConfig''', '''MBartOnnxConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''MBartTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''MBartTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''MBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MBartForCausalLM''', '''MBartForConditionalGeneration''', '''MBartForQuestionAnswering''', '''MBartForSequenceClassification''', '''MBartModel''', '''MBartPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TFMBartForConditionalGeneration''', '''TFMBartModel''', '''TFMBartPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FlaxMBartForConditionalGeneration''', '''FlaxMBartForQuestionAnswering''', '''FlaxMBartForSequenceClassification''', '''FlaxMBartModel''', '''FlaxMBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __snake_case ( _lowercase): snake_case__ : torch.FloatTensor snake_case__ : torch.FloatTensor class __snake_case ( _lowercase , _lowercase): snake_case__ : int = 1 @register_to_config def __init__( self : str , __lowerCAmelCase : int = 2_0_0_0 , __lowerCAmelCase : float = 0.15 , __lowerCAmelCase : float = 0.01 , __lowerCAmelCase : float = 13_48.0 , __lowerCAmelCase : float = 1E-5 , __lowerCAmelCase : int = 1 , ): """simple docstring""" _lowerCamelCase : Optional[int] = sigma_max # setable values _lowerCamelCase : Dict = None self.set_sigmas(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : Union[str, torch.device] = None ): """simple docstring""" _lowerCamelCase : Tuple = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCamelCase : Optional[int] = torch.linspace(1 , __lowerCAmelCase , __lowerCAmelCase , device=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None ): """simple docstring""" _lowerCamelCase : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCamelCase : int = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCamelCase : Optional[int] = torch.exp(torch.linspace(math.log(__lowerCAmelCase ) , math.log(__lowerCAmelCase ) , __lowerCAmelCase ) ) _lowerCamelCase : Tuple = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : int , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) _lowerCamelCase : Tuple = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCamelCase : Dict = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCamelCase : Optional[int] = timesteps.to(self.discrete_sigmas.device ) _lowerCamelCase : Any = self.discrete_sigmas[timesteps].to(sample.device ) _lowerCamelCase : int = self.get_adjacent_sigma(__lowerCAmelCase , __lowerCAmelCase ).to(sample.device ) _lowerCamelCase : Any = torch.zeros_like(__lowerCAmelCase ) _lowerCamelCase : Any = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCamelCase : Union[str, Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): _lowerCamelCase : List[Any] = diffusion.unsqueeze(-1 ) _lowerCamelCase : int = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCamelCase : List[str] = randn_tensor( sample.shape , layout=sample.layout , generator=__lowerCAmelCase , device=sample.device , dtype=sample.dtype ) _lowerCamelCase : List[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCamelCase : int = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=__lowerCAmelCase , prev_sample_mean=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCamelCase : Union[str, Any] = randn_tensor(sample.shape , layout=sample.layout , generator=__lowerCAmelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr _lowerCamelCase : Union[str, Any] = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : str = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCamelCase : Tuple = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): _lowerCamelCase : str = step_size.unsqueeze(-1 ) _lowerCamelCase : Any = sample + step_size * model_output _lowerCamelCase : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , ): """simple docstring""" _lowerCamelCase : Dict = timesteps.to(original_samples.device ) _lowerCamelCase : Union[str, Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] _lowerCamelCase : Union[str, Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(__lowerCAmelCase ) * sigmas[:, None, None, None] ) _lowerCamelCase : int = noise + original_samples return noisy_samples def __len__( self : Optional[int] ): """simple docstring""" return self.config.num_train_timesteps
83
1
"""simple docstring""" from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
83
"""simple docstring""" from torch import nn def snake_case_ ( A_ : int ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'''Unsupported activation function: {act_fn}''' )
83
1
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class __snake_case : snake_case__ : CommonSchedulerState # setable values snake_case__ : jnp.ndarray snake_case__ : jnp.ndarray snake_case__ : Optional[int] = None @classmethod def SCREAMING_SNAKE_CASE ( cls : List[str] , __lowerCAmelCase : CommonSchedulerState , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray ): """simple docstring""" return cls(common=__lowerCAmelCase , init_noise_sigma=__lowerCAmelCase , timesteps=__lowerCAmelCase ) @dataclass class __snake_case ( _lowercase): snake_case__ : DDPMSchedulerState class __snake_case ( _lowercase , _lowercase): snake_case__ : Union[str, Any] = [e.name for e in FlaxKarrasDiffusionSchedulers] snake_case__ : jnp.dtype @property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return True @register_to_config def __init__( self : List[str] , __lowerCAmelCase : int = 1_0_0_0 , __lowerCAmelCase : float = 0.00_01 , __lowerCAmelCase : float = 0.02 , __lowerCAmelCase : str = "linear" , __lowerCAmelCase : Optional[jnp.ndarray] = None , __lowerCAmelCase : str = "fixed_small" , __lowerCAmelCase : bool = True , __lowerCAmelCase : str = "epsilon" , __lowerCAmelCase : jnp.dtype = jnp.floataa , ): """simple docstring""" _lowerCamelCase : Optional[int] = dtype def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Optional[CommonSchedulerState] = None ): """simple docstring""" if common is None: _lowerCamelCase : List[Any] = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution _lowerCamelCase : Dict = jnp.array(1.0 , dtype=self.dtype ) _lowerCamelCase : Union[str, Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__lowerCAmelCase , init_noise_sigma=__lowerCAmelCase , timesteps=__lowerCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : DDPMSchedulerState , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : DDPMSchedulerState , __lowerCAmelCase : int , __lowerCAmelCase : Tuple = () ): """simple docstring""" _lowerCamelCase : Tuple = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 _lowerCamelCase : Any = (jnp.arange(0 , __lowerCAmelCase ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__lowerCAmelCase , timesteps=__lowerCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : DDPMSchedulerState , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple=None , __lowerCAmelCase : int=None ): """simple docstring""" _lowerCamelCase : str = state.common.alphas_cumprod[t] _lowerCamelCase : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _lowerCamelCase : List[str] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: _lowerCamelCase : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": _lowerCamelCase : Optional[Any] = jnp.clip(__lowerCAmelCase , a_min=1E-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": _lowerCamelCase : Optional[Any] = jnp.log(jnp.clip(__lowerCAmelCase , a_min=1E-20 ) ) elif variance_type == "fixed_large": _lowerCamelCase : List[str] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log _lowerCamelCase : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": _lowerCamelCase : Dict = variance _lowerCamelCase : Union[str, Any] = state.common.betas[t] _lowerCamelCase : Union[str, Any] = (predicted_variance + 1) / 2 _lowerCamelCase : Optional[int] = frac * max_log + (1 - frac) * min_log return variance def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : DDPMSchedulerState , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : int , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : Optional[jax.random.KeyArray] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" _lowerCamelCase : str = timestep if key is None: _lowerCamelCase : List[Any] = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: _lowerCamelCase , _lowerCamelCase : Dict = jnp.split(__lowerCAmelCase , sample.shape[1] , axis=1 ) else: _lowerCamelCase : Union[str, Any] = None # 1. compute alphas, betas _lowerCamelCase : str = state.common.alphas_cumprod[t] _lowerCamelCase : Tuple = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) _lowerCamelCase : Optional[Any] = 1 - alpha_prod_t _lowerCamelCase : Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _lowerCamelCase : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _lowerCamelCase : Dict = model_output elif self.config.prediction_type == "v_prediction": _lowerCamelCase : int = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: _lowerCamelCase : Tuple = jnp.clip(__lowerCAmelCase , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _lowerCamelCase : Any = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t _lowerCamelCase : List[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _lowerCamelCase : List[str] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): _lowerCamelCase : Dict = jax.random.split(__lowerCAmelCase , num=1 ) _lowerCamelCase : List[str] = jax.random.normal(__lowerCAmelCase , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__lowerCAmelCase , __lowerCAmelCase , predicted_variance=__lowerCAmelCase ) ** 0.5) * noise _lowerCamelCase : List[str] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) _lowerCamelCase : Union[str, Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__lowerCAmelCase , state=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : DDPMSchedulerState , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , ): """simple docstring""" return add_noise_common(state.common , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : DDPMSchedulerState , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , __lowerCAmelCase : jnp.ndarray , ): """simple docstring""" return get_velocity_common(state.common , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def __len__( self : List[Any] ): """simple docstring""" return self.config.num_train_timesteps
83
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def snake_case_ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(F'''| 0 | 0 | {nor_gate(0, 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0, 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1, 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1, 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
83
1
"""simple docstring""" 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 __snake_case ( _lowercase): @slow @require_torch def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = EncoderDecoderModel.from_encoder_decoder_pretrained('''prajjwal1/bert-tiny''' , '''prajjwal1/bert-tiny''' ) _lowerCamelCase : Optional[Any] = BertTokenizer.from_pretrained('''bert-base-uncased''' ) _lowerCamelCase : List[Any] = bertabert.config.encoder.vocab_size _lowerCamelCase : Optional[int] = tokenizer.sep_token_id _lowerCamelCase : Any = tokenizer.cls_token_id _lowerCamelCase : Tuple = 1_2_8 _lowerCamelCase : str = datasets.load_dataset('''cnn_dailymail''' , '''3.0.0''' , split='''train[:1%]''' ) _lowerCamelCase : List[Any] = datasets.load_dataset('''cnn_dailymail''' , '''3.0.0''' , split='''validation[:1%]''' ) _lowerCamelCase : Union[str, Any] = train_dataset.select(range(3_2 ) ) _lowerCamelCase : Tuple = val_dataset.select(range(1_6 ) ) _lowerCamelCase : Optional[Any] = 4 def _map_to_encoder_decoder_inputs(__lowerCAmelCase : Union[str, Any] ): # Tokenizer will automatically set [BOS] <text> [EOS] _lowerCamelCase : Union[str, Any] = tokenizer(batch['''article'''] , padding='''max_length''' , truncation=__lowerCAmelCase , max_length=5_1_2 ) _lowerCamelCase : Optional[Any] = tokenizer(batch['''highlights'''] , padding='''max_length''' , truncation=__lowerCAmelCase , max_length=1_2_8 ) _lowerCamelCase : Union[str, Any] = inputs.input_ids _lowerCamelCase : Dict = inputs.attention_mask _lowerCamelCase : Union[str, Any] = outputs.input_ids _lowerCamelCase : Optional[int] = outputs.input_ids.copy() _lowerCamelCase : List[str] = [ [-1_0_0 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch['''labels'''] ] _lowerCamelCase : List[Any] = outputs.attention_mask assert all(len(__lowerCAmelCase ) == 5_1_2 for x in inputs.input_ids ) assert all(len(__lowerCAmelCase ) == 1_2_8 for x in outputs.input_ids ) return batch def _compute_metrics(__lowerCAmelCase : List[str] ): _lowerCamelCase : Union[str, Any] = pred.label_ids _lowerCamelCase : List[Any] = pred.predictions # all unnecessary tokens are removed _lowerCamelCase : Optional[int] = tokenizer.batch_decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) _lowerCamelCase : Tuple = tokenizer.batch_decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) _lowerCamelCase : List[str] = sum([int(pred_str[i] == label_str[i] ) for i in range(len(__lowerCAmelCase ) )] ) / len(__lowerCAmelCase ) return {"accuracy": accuracy} # map train dataset _lowerCamelCase : Optional[Any] = train_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCAmelCase , batch_size=__lowerCAmelCase , 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 _lowerCamelCase : Union[str, Any] = val_dataset.map( _map_to_encoder_decoder_inputs , batched=__lowerCAmelCase , batch_size=__lowerCAmelCase , remove_columns=['''article''', '''highlights'''] , ) val_dataset.set_format( type='''torch''' , columns=['''input_ids''', '''attention_mask''', '''decoder_input_ids''', '''decoder_attention_mask''', '''labels'''] , ) _lowerCamelCase : Any = self.get_auto_remove_tmp_dir() _lowerCamelCase : Dict = SeqaSeqTrainingArguments( output_dir=__lowerCAmelCase , per_device_train_batch_size=__lowerCAmelCase , per_device_eval_batch_size=__lowerCAmelCase , predict_with_generate=__lowerCAmelCase , evaluation_strategy='''steps''' , do_train=__lowerCAmelCase , do_eval=__lowerCAmelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer _lowerCamelCase : Optional[Any] = SeqaSeqTrainer( model=__lowerCAmelCase , args=__lowerCAmelCase , compute_metrics=_compute_metrics , train_dataset=__lowerCAmelCase , eval_dataset=__lowerCAmelCase , tokenizer=__lowerCAmelCase , ) # start training trainer.train()
83
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : list[list[int]] ): '''simple docstring''' for i in range(1, len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(A_ ) ): for j in range(1, len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel lowerCAmelCase__ = '''0.12''' # assumed parallelism: 8 @require_flax @is_staging_test class __snake_case ( unittest.TestCase): @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] ): """simple docstring""" _lowerCamelCase : Tuple = TOKEN HfFolder.save_token(__lowerCAmelCase ) @classmethod def SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ): """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-model-flax''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-model-flax-org''' ) except HTTPError: pass def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Any = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) _lowerCamelCase : Any = FlaxBertModel(__lowerCAmelCase ) model.push_to_hub('''test-model-flax''' , use_auth_token=self._token ) _lowerCamelCase : Union[str, Any] = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) _lowerCamelCase : List[Any] = flatten_dict(unfreeze(model.params ) ) _lowerCamelCase : Tuple = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _lowerCamelCase : int = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCAmelCase , 1E-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id='''test-model-flax''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__lowerCAmelCase , repo_id='''test-model-flax''' , push_to_hub=__lowerCAmelCase , use_auth_token=self._token ) _lowerCamelCase : Dict = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) _lowerCamelCase : Tuple = flatten_dict(unfreeze(model.params ) ) _lowerCamelCase : Tuple = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _lowerCamelCase : Optional[Any] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCAmelCase , 1E-3 , msg=f'''{key} not identical''' ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) _lowerCamelCase : Optional[int] = FlaxBertModel(__lowerCAmelCase ) model.push_to_hub('''valid_org/test-model-flax-org''' , use_auth_token=self._token ) _lowerCamelCase : Optional[Any] = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) _lowerCamelCase : int = flatten_dict(unfreeze(model.params ) ) _lowerCamelCase : Dict = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _lowerCamelCase : Optional[Any] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCAmelCase , 1E-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-model-flax-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( __lowerCAmelCase , repo_id='''valid_org/test-model-flax-org''' , push_to_hub=__lowerCAmelCase , use_auth_token=self._token ) _lowerCamelCase : List[Any] = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) _lowerCamelCase : Tuple = flatten_dict(unfreeze(model.params ) ) _lowerCamelCase : List[Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _lowerCamelCase : str = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__lowerCAmelCase , 1E-3 , msg=f'''{key} not identical''' ) def snake_case_ ( A_ : Any, A_ : str ): '''simple docstring''' _lowerCamelCase : Tuple = True _lowerCamelCase : List[Any] = flatten_dict(modela.params ) _lowerCamelCase : str = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: _lowerCamelCase : int = False return models_are_equal @require_flax class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Union[str, Any] = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) _lowerCamelCase : Any = FlaxBertModel(__lowerCAmelCase ) _lowerCamelCase : Any = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : str = FlaxBertModel.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = FlaxBertModel.from_pretrained(__lowerCAmelCase , subfolder=__lowerCAmelCase ) self.assertTrue(check_models_equal(__lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : List[Any] = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) _lowerCamelCase : Tuple = FlaxBertModel(__lowerCAmelCase ) _lowerCamelCase : Tuple = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) , max_shard_size='''10KB''' ) with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Optional[int] = FlaxBertModel.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : Dict = FlaxBertModel.from_pretrained(__lowerCAmelCase , subfolder=__lowerCAmelCase ) self.assertTrue(check_models_equal(__lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = '''bert''' _lowerCamelCase : Union[str, Any] = '''hf-internal-testing/tiny-random-bert-subfolder''' with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Optional[Any] = FlaxBertModel.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = FlaxBertModel.from_pretrained(__lowerCAmelCase , subfolder=__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = '''bert''' _lowerCamelCase : Tuple = '''hf-internal-testing/tiny-random-bert-sharded-subfolder''' with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : str = FlaxBertModel.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = FlaxBertModel.from_pretrained(__lowerCAmelCase , subfolder=__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase )
83
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Optional[int] = data _lowerCamelCase : Node[T] | None = None def __str__( self : Optional[Any] ): """simple docstring""" return f'''{self.data}''' class __snake_case ( Generic[T]): def __init__( self : int ): """simple docstring""" _lowerCamelCase : Node[T] | None = None def __iter__( self : str ): """simple docstring""" _lowerCamelCase : List[str] = self.top while node: yield node.data _lowerCamelCase : Any = node.next def __str__( self : int ): """simple docstring""" return "->".join([str(__lowerCAmelCase ) for item in self] ) def __len__( self : int ): """simple docstring""" return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.top is None def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Tuple = Node(__lowerCAmelCase ) if not self.is_empty(): _lowerCamelCase : Optional[int] = self.top _lowerCamelCase : List[str] = node def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , __lowerCAmelCase ) _lowerCamelCase : Any = self.top _lowerCamelCase : Any = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = None if __name__ == "__main__": from doctest import testmod testmod()
83
1
"""simple docstring""" import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' return EnvironmentCommand() def snake_case_ ( A_ : List[str] ): '''simple docstring''' return EnvironmentCommand(args.accelerate_config_file ) class __snake_case ( _lowercase): @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : ArgumentParser ): """simple docstring""" _lowerCamelCase : List[str] = parser.add_parser('''env''' ) download_parser.set_defaults(func=__lowerCAmelCase ) download_parser.add_argument( '''--accelerate-config_file''' , default=__lowerCAmelCase , help='''The accelerate config file to use for the default values in the launching script.''' , ) download_parser.set_defaults(func=__lowerCAmelCase ) def __init__( self : List[str] , __lowerCAmelCase : Optional[int] , *__lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : str = accelerate_config_file def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Dict = '''not installed''' if is_safetensors_available(): import safetensors _lowerCamelCase : List[Any] = safetensors.__version__ elif importlib.util.find_spec('''safetensors''' ) is not None: import safetensors _lowerCamelCase : List[Any] = f'''{safetensors.__version__} but is ignored because of PyTorch version too old.''' _lowerCamelCase : Optional[Any] = '''not installed''' _lowerCamelCase : List[Any] = '''not found''' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file _lowerCamelCase : List[Any] = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__lowerCAmelCase ): _lowerCamelCase : List[Any] = load_config_from_file(self._accelerate_config_file ).to_dict() _lowerCamelCase : Tuple = ( '''\n'''.join([f'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else f'''\t{accelerate_config}''' ) _lowerCamelCase : Dict = '''not installed''' _lowerCamelCase : Any = '''NA''' if is_torch_available(): import torch _lowerCamelCase : Union[str, Any] = torch.__version__ _lowerCamelCase : Dict = torch.cuda.is_available() _lowerCamelCase : Optional[int] = '''not installed''' _lowerCamelCase : List[str] = '''NA''' if is_tf_available(): import tensorflow as tf _lowerCamelCase : int = tf.__version__ try: # deprecated in v2.1 _lowerCamelCase : Optional[Any] = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool _lowerCamelCase : Any = bool(tf.config.list_physical_devices('''GPU''' ) ) _lowerCamelCase : Tuple = '''not installed''' _lowerCamelCase : Any = '''not installed''' _lowerCamelCase : Optional[int] = '''not installed''' _lowerCamelCase : Optional[int] = '''NA''' if is_flax_available(): import flax import jax import jaxlib _lowerCamelCase : Union[str, Any] = flax.__version__ _lowerCamelCase : Optional[int] = jax.__version__ _lowerCamelCase : Any = jaxlib.__version__ _lowerCamelCase : Any = jax.lib.xla_bridge.get_backend().platform _lowerCamelCase : str = { '''`transformers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Huggingface_hub version''': huggingface_hub.__version__, '''Safetensors version''': f'''{safetensors_version}''', '''Accelerate version''': f'''{accelerate_version}''', '''Accelerate config''': f'''{accelerate_config_str}''', '''PyTorch version (GPU?)''': f'''{pt_version} ({pt_cuda_available})''', '''Tensorflow version (GPU?)''': f'''{tf_version} ({tf_cuda_available})''', '''Flax version (CPU?/GPU?/TPU?)''': f'''{flax_version} ({jax_backend})''', '''Jax version''': f'''{jax_version}''', '''JaxLib version''': f'''{jaxlib_version}''', '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(__lowerCAmelCase ) ) return info @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : Dict ): """simple docstring""" return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
83
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase__ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCAmelCase__ = spec.loader.load_module() lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCAmelCase__ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = [] for config_class in list(CONFIG_MAPPING.values() ): _lowerCamelCase : Tuple = False # source code of `config_class` _lowerCamelCase : int = inspect.getsource(A_ ) _lowerCamelCase : str = _re_checkpoint.findall(A_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` _lowerCamelCase , _lowerCamelCase : Tuple = checkpoint # verify the checkpoint name corresponds to the checkpoint link _lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _lowerCamelCase : Union[str, Any] = True break _lowerCamelCase : Tuple = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
83
1
"""simple docstring""" from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class __snake_case : def __init__( self : str , __lowerCAmelCase : Collection[float] | None = None ): """simple docstring""" if components is None: _lowerCamelCase : Tuple = [] _lowerCamelCase : int = list(__lowerCAmelCase ) def __len__( self : Tuple ): """simple docstring""" return len(self.__components ) def __str__( self : str ): """simple docstring""" return "(" + ",".join(map(__lowerCAmelCase , self.__components ) ) + ")" def __add__( self : Dict , __lowerCAmelCase : Vector ): """simple docstring""" _lowerCamelCase : List[str] = len(self ) if size == len(__lowerCAmelCase ): _lowerCamelCase : Union[str, Any] = [self.__components[i] + other.component(__lowerCAmelCase ) for i in range(__lowerCAmelCase )] return Vector(__lowerCAmelCase ) else: raise Exception('''must have the same size''' ) def __sub__( self : List[Any] , __lowerCAmelCase : Vector ): """simple docstring""" _lowerCamelCase : str = len(self ) if size == len(__lowerCAmelCase ): _lowerCamelCase : Tuple = [self.__components[i] - other.component(__lowerCAmelCase ) for i in range(__lowerCAmelCase )] return Vector(__lowerCAmelCase ) else: # error case raise Exception('''must have the same size''' ) @overload def __mul__( self : Optional[Any] , __lowerCAmelCase : float ): """simple docstring""" ... @overload def __mul__( self : Union[str, Any] , __lowerCAmelCase : Vector ): """simple docstring""" ... def __mul__( self : Optional[int] , __lowerCAmelCase : float | Vector ): """simple docstring""" if isinstance(__lowerCAmelCase , (float, int) ): _lowerCamelCase : Any = [c * other for c in self.__components] return Vector(__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ) and len(self ) == len(__lowerCAmelCase ): _lowerCamelCase : int = len(self ) _lowerCamelCase : int = [self.__components[i] * other.component(__lowerCAmelCase ) for i in range(__lowerCAmelCase )] return sum(__lowerCAmelCase ) else: # error case raise Exception('''invalid operand!''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return Vector(self.__components ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : int ): """simple docstring""" if isinstance(__lowerCAmelCase , __lowerCAmelCase ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('''index out of range''' ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : int , __lowerCAmelCase : float ): """simple docstring""" assert -len(self.__components ) <= pos < len(self.__components ) _lowerCamelCase : List[Any] = value def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" if len(self.__components ) == 0: raise Exception('''Vector is empty''' ) _lowerCamelCase : Any = [c**2 for c in self.__components] return math.sqrt(sum(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Vector , __lowerCAmelCase : bool = False ): """simple docstring""" _lowerCamelCase : Optional[int] = self * other _lowerCamelCase : Tuple = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def snake_case_ ( A_ : int ): '''simple docstring''' assert isinstance(A_, A_ ) return Vector([0] * dimension ) def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' assert isinstance(A_, A_ ) and (isinstance(A_, A_ )) _lowerCamelCase : Any = [0] * dimension _lowerCamelCase : str = 1 return Vector(A_ ) def snake_case_ ( A_ : float, A_ : Vector, A_ : Vector ): '''simple docstring''' assert ( isinstance(A_, A_ ) and isinstance(A_, A_ ) and (isinstance(A_, (int, float) )) ) return x * scalar + y def snake_case_ ( A_ : int, A_ : int, A_ : int ): '''simple docstring''' random.seed(A_ ) _lowerCamelCase : Tuple = [random.randint(A_, A_ ) for _ in range(A_ )] return Vector(A_ ) class __snake_case : def __init__( self : Optional[Any] , __lowerCAmelCase : list[list[float]] , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : str = matrix _lowerCamelCase : str = w _lowerCamelCase : Union[str, Any] = h def __str__( self : int ): """simple docstring""" _lowerCamelCase : Optional[Any] = '''''' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : Optional[Any] , __lowerCAmelCase : Matrix ): """simple docstring""" if self.__width == other.width() and self.__height == other.height(): _lowerCamelCase : Optional[int] = [] for i in range(self.__height ): _lowerCamelCase : Dict = [ self.__matrix[i][j] + other.component(__lowerCAmelCase , __lowerCAmelCase ) for j in range(self.__width ) ] matrix.append(__lowerCAmelCase ) return Matrix(__lowerCAmelCase , self.__width , self.__height ) else: raise Exception('''matrix must have the same dimension!''' ) def __sub__( self : List[Any] , __lowerCAmelCase : Matrix ): """simple docstring""" if self.__width == other.width() and self.__height == other.height(): _lowerCamelCase : List[Any] = [] for i in range(self.__height ): _lowerCamelCase : List[str] = [ self.__matrix[i][j] - other.component(__lowerCAmelCase , __lowerCAmelCase ) for j in range(self.__width ) ] matrix.append(__lowerCAmelCase ) return Matrix(__lowerCAmelCase , self.__width , self.__height ) else: raise Exception('''matrices must have the same dimension!''' ) @overload def __mul__( self : Any , __lowerCAmelCase : float ): """simple docstring""" ... @overload def __mul__( self : Tuple , __lowerCAmelCase : Vector ): """simple docstring""" ... def __mul__( self : Optional[int] , __lowerCAmelCase : float | Vector ): """simple docstring""" if isinstance(__lowerCAmelCase , __lowerCAmelCase ): # matrix-vector if len(__lowerCAmelCase ) == self.__width: _lowerCamelCase : Optional[Any] = zero_vector(self.__height ) for i in range(self.__height ): _lowerCamelCase : str = [ self.__matrix[i][j] * other.component(__lowerCAmelCase ) for j in range(self.__width ) ] ans.change_component(__lowerCAmelCase , sum(__lowerCAmelCase ) ) return ans else: raise Exception( '''vector must have the same size as the ''' '''number of columns of the matrix!''' ) elif isinstance(__lowerCAmelCase , (int, float) ): # matrix-scalar _lowerCamelCase : Optional[Any] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(__lowerCAmelCase , self.__width , self.__height ) return None def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.__height def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.__width def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('''change_component: indices out of bounds''' ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : float ): """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: _lowerCamelCase : Tuple = value else: raise Exception('''change_component: indices out of bounds''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" if self.__height != self.__width: raise Exception('''Matrix is not square''' ) _lowerCamelCase : List[Any] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__lowerCAmelCase ) ): _lowerCamelCase : int = minor[i][:y] + minor[i][y + 1 :] return Matrix(__lowerCAmelCase , self.__width - 1 , self.__height - 1 ).determinant() def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" if self.__height != self.__width: raise Exception('''Matrix is not square''' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__lowerCAmelCase , __lowerCAmelCase ) else: raise Exception('''Indices out of bounds''' ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if self.__height != self.__width: raise Exception('''Matrix is not square''' ) if self.__height < 1: raise Exception('''Matrix has no element''' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: _lowerCamelCase : Optional[Any] = [ self.__matrix[0][y] * self.cofactor(0 , __lowerCAmelCase ) for y in range(self.__width ) ] return sum(__lowerCAmelCase ) def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : list[list[float]] = [[0] * n for _ in range(A_ )] return Matrix(A_, A_, A_ ) def snake_case_ ( A_ : int, A_ : int, A_ : int, A_ : int ): '''simple docstring''' random.seed(A_ ) _lowerCamelCase : list[list[float]] = [ [random.randint(A_, A_ ) for _ in range(A_ )] for _ in range(A_ ) ] return Matrix(A_, A_, A_ )
83
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class __snake_case ( unittest.TestCase): pass @nightly @require_torch_gpu class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : int = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : str = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Dict = torch.manual_seed(0 ) _lowerCamelCase : List[Any] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : int = generator.manual_seed(0 ) _lowerCamelCase : List[str] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Optional[int] = torch.manual_seed(0 ) _lowerCamelCase : int = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images _lowerCamelCase : List[str] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Dict = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
83
1
"""simple docstring""" def snake_case_ ( A_ : Optional[int], A_ : Optional[int], A_ : Any, A_ : Optional[int] ): '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: _lowerCamelCase : Optional[Any] = mf_knapsack(i - 1, A_, A_, A_ ) else: _lowerCamelCase : Optional[int] = max( mf_knapsack(i - 1, A_, A_, A_ ), mf_knapsack(i - 1, A_, A_, j - wt[i - 1] ) + val[i - 1], ) _lowerCamelCase : Dict = val return f[i][j] def snake_case_ ( A_ : int, A_ : Any, A_ : List[str], A_ : str ): '''simple docstring''' _lowerCamelCase : Optional[int] = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1, n + 1 ): for w_ in range(1, w + 1 ): if wt[i - 1] <= w_: _lowerCamelCase : Any = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_] ) else: _lowerCamelCase : Tuple = dp[i - 1][w_] return dp[n][w_], dp def snake_case_ ( A_ : int, A_ : list, A_ : list ): '''simple docstring''' if not (isinstance(A_, (list, tuple) ) and isinstance(A_, (list, tuple) )): raise ValueError( '''Both the weights and values vectors must be either lists or tuples''' ) _lowerCamelCase : Optional[Any] = len(A_ ) if num_items != len(A_ ): _lowerCamelCase : Union[str, Any] = ( '''The number of weights must be the same as the number of values.\n''' F'''But got {num_items} weights and {len(A_ )} values''' ) raise ValueError(A_ ) for i in range(A_ ): if not isinstance(wt[i], A_ ): _lowerCamelCase : int = ( '''All weights must be integers but got weight of ''' F'''type {type(wt[i] )} at index {i}''' ) raise TypeError(A_ ) _lowerCamelCase , _lowerCamelCase : int = knapsack(A_, A_, A_, A_ ) _lowerCamelCase : set = set() _construct_solution(A_, A_, A_, A_, A_ ) return optimal_val, example_optional_set def snake_case_ ( A_ : list, A_ : list, A_ : int, A_ : int, A_ : set ): '''simple docstring''' if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(A_, A_, i - 1, A_, A_ ) else: optimal_set.add(A_ ) _construct_solution(A_, A_, i - 1, j - wt[i - 1], A_ ) if __name__ == "__main__": lowerCAmelCase__ = [3, 2, 4, 4] lowerCAmelCase__ = [4, 3, 2, 3] lowerCAmelCase__ = 4 lowerCAmelCase__ = 6 lowerCAmelCase__ = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] lowerCAmelCase__ , lowerCAmelCase__ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 lowerCAmelCase__ , lowerCAmelCase__ = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('''optimal_value = ''', optimal_solution) print('''An optimal subset corresponding to the optimal value''', optimal_subset)
83
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = '''1''' lowerCAmelCase__ = '''0''' lowerCAmelCase__ = '''1''' lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('''Create inference session...''') lowerCAmelCase__ = ['''TensorrtExecutionProvider''', '''CUDAExecutionProvider'''] lowerCAmelCase__ = ort.InferenceSession('''model.onnx''', sess_options=sess_opt, providers=execution_provider) lowerCAmelCase__ = ort.RunOptions() lowerCAmelCase__ = 128 lowerCAmelCase__ = 1 lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) print('''Warm up phase...''') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Start inference...''') lowerCAmelCase__ = time.time() lowerCAmelCase__ = 2000 lowerCAmelCase__ = {} for iter in range(max_iters): lowerCAmelCase__ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Average Inference Time = {:.3f} ms'''.format((time.time() - start_time) * 1000 / max_iters))
83
1
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case ( _lowercase): def __init__( self : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=9_9 , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : Optional[int]=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : int=5_1_2 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any="None" , __lowerCAmelCase : str=3 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[Any]=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Dict = use_input_mask _lowerCamelCase : Tuple = use_token_type_ids _lowerCamelCase : Optional[Any] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Optional[int] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : int = relative_attention _lowerCamelCase : Union[str, Any] = position_biased_input _lowerCamelCase : str = pos_att_type _lowerCamelCase : Tuple = scope def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : int = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : str = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : List[Any] = model(__lowerCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : Dict = DebertaVaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : Tuple = DebertaVaForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = DebertaVaForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : int = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True snake_case__ : List[Any] = False snake_case__ : int = False snake_case__ : Optional[Any] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) _lowerCamelCase : List[str] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] # compare the actual values for a slice. _lowerCamelCase : Union[str, Any] = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
83
"""simple docstring""" import colorsys from PIL import Image # type: ignore def snake_case_ ( A_ : float, A_ : float, A_ : int ): '''simple docstring''' _lowerCamelCase : List[Any] = x _lowerCamelCase : List[Any] = y for step in range(A_ ): # noqa: B007 _lowerCamelCase : Dict = a * a - b * b + x _lowerCamelCase : List[str] = 2 * a * b + y _lowerCamelCase : Any = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def snake_case_ ( A_ : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(A_, 1, 1 ) ) def snake_case_ ( A_ : int = 8_00, A_ : int = 6_00, A_ : float = -0.6, A_ : float = 0, A_ : float = 3.2, A_ : int = 50, A_ : bool = True, ): '''simple docstring''' _lowerCamelCase : Tuple = Image.new('''RGB''', (image_width, image_height) ) _lowerCamelCase : int = img.load() # loop through the image-coordinates for image_x in range(A_ ): for image_y in range(A_ ): # determine the figure-coordinates based on the image-coordinates _lowerCamelCase : Optional[Any] = figure_width / image_width * image_height _lowerCamelCase : List[Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width _lowerCamelCase : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height _lowerCamelCase : str = get_distance(A_, A_, A_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: _lowerCamelCase : Dict = get_color_coded_rgb(A_ ) else: _lowerCamelCase : str = get_black_and_white_rgb(A_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCAmelCase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
83
1
"""simple docstring""" import heapq def snake_case_ ( A_ : dict ): '''simple docstring''' _lowerCamelCase : list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(A_, [-1 * len(A_ ), (key, value)] ) # chosen_vertices = set of chosen vertices _lowerCamelCase : str = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices _lowerCamelCase : Dict = heapq.heappop(A_ )[1][0] chosen_vertices.add(A_ ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: _lowerCamelCase : List[str] = elem[1][1].index(A_ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(A_ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F"""Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}""")
83
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ): '''simple docstring''' _lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {} _lowerCamelCase : Union[str, Any] = padding_side return tokenizer( [line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, ) def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ): '''simple docstring''' _lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ): """simple docstring""" super().__init__() _lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' ) _lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' ) _lowerCamelCase : List[Any] = self.get_char_lens(self.src_file ) _lowerCamelCase : Optional[int] = max_source_length _lowerCamelCase : Optional[Any] = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _lowerCamelCase : List[Any] = tokenizer _lowerCamelCase : List[Any] = prefix if n_obs is not None: _lowerCamelCase : List[str] = self.src_lens[:n_obs] _lowerCamelCase : int = src_lang _lowerCamelCase : Union[str, Any] = tgt_lang def __len__( self : int ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = index + 1 # linecache starts at 1 _lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' ) _lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowerCAmelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _lowerCamelCase : Optional[int] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer ) _lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' ) _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' ) _lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze() _lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() _lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ): """simple docstring""" return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) _lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowerCAmelCase__ = getLogger(__name__) def snake_case_ ( A_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(A_ ) ) def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Dict = get_git_info() save_json(A_, os.path.join(A_, '''git_log.json''' ) ) def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ): '''simple docstring''' with open(A_, '''w''' ) as f: json.dump(A_, A_, indent=A_, **A_ ) def snake_case_ ( A_ : Any ): '''simple docstring''' with open(A_ ) as f: return json.load(A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ ) _lowerCamelCase : str = { '''repo_id''': str(A_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case_ ( A_ : Callable, A_ : Iterable ): '''simple docstring''' return list(map(A_, A_ ) ) def snake_case_ ( A_ : str, A_ : Tuple ): '''simple docstring''' with open(A_, '''wb''' ) as f: return pickle.dump(A_, A_ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' def remove_articles(A_ : str ): return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ ) def white_space_fix(A_ : Any ): return " ".join(text.split() ) def remove_punc(A_ : List[Any] ): _lowerCamelCase : Any = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case_ ( A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : str = normalize_answer(A_ ).split() _lowerCamelCase : int = normalize_answer(A_ ).split() _lowerCamelCase : str = Counter(A_ ) & Counter(A_ ) _lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 _lowerCamelCase : int = 1.0 * num_same / len(A_ ) _lowerCamelCase : str = 1.0 * num_same / len(A_ ) _lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case_ ( A_ : Dict, A_ : str ): '''simple docstring''' return normalize_answer(A_ ) == normalize_answer(A_ ) def snake_case_ ( A_ : List[str], A_ : List[str] ): '''simple docstring''' assert len(A_ ) == len(A_ ) _lowerCamelCase : Optional[Any] = 0 for hypo, pred in zip(A_, A_ ): em += exact_match_score(A_, A_ ) if len(A_ ) > 0: em /= len(A_ ) return {"em": em} def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Dict = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _lowerCamelCase : Tuple = '''dropout_rate''' for p in extra_params: if getattr(A_, A_, A_ ): if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) ) delattr(A_, A_ ) continue _lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p] setattr(A_, A_, getattr(A_, A_ ) ) delattr(A_, A_ ) return hparams, config
83
1
"""simple docstring""" def snake_case_ ( A_ : list, A_ : list, A_ : int, A_ : int, A_ : int ): '''simple docstring''' if index == number_of_items: return 0 _lowerCamelCase : int = 0 _lowerCamelCase : str = 0 _lowerCamelCase : Dict = knapsack(A_, A_, A_, A_, index + 1 ) if weights[index] <= max_weight: _lowerCamelCase : Tuple = values[index] + knapsack( A_, A_, A_, max_weight - weights[index], index + 1 ) return max(A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "camembert" def __init__( self : Optional[Any] , __lowerCAmelCase : Any=3_0_5_2_2 , __lowerCAmelCase : List[str]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : List[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Optional[int]=5_1_2 , __lowerCAmelCase : str=2 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : List[Any]=1E-12 , __lowerCAmelCase : Union[str, Any]=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : str="absolute" , __lowerCAmelCase : Any=True , __lowerCAmelCase : Optional[int]=None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Optional[Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : List[str] = classifier_dropout class __snake_case ( _lowercase): @property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self.task == "multiple-choice": _lowerCamelCase : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _lowerCamelCase : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
83
1
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ): '''simple docstring''' _lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {} _lowerCamelCase : Union[str, Any] = padding_side return tokenizer( [line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, ) def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ): '''simple docstring''' _lowerCamelCase : Optional[int] = input_ids.ne(A_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ): """simple docstring""" super().__init__() _lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' ) _lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' ) _lowerCamelCase : List[Any] = self.get_char_lens(self.src_file ) _lowerCamelCase : Optional[int] = max_source_length _lowerCamelCase : Optional[Any] = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _lowerCamelCase : List[Any] = tokenizer _lowerCamelCase : List[Any] = prefix if n_obs is not None: _lowerCamelCase : List[str] = self.src_lens[:n_obs] _lowerCamelCase : int = src_lang _lowerCamelCase : Union[str, Any] = tgt_lang def __len__( self : int ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = index + 1 # linecache starts at 1 _lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' ) _lowerCamelCase : Optional[Any] = linecache.getline(str(self.tgt_file ) , __lowerCAmelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowerCAmelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _lowerCamelCase : Optional[int] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer ) _lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' ) _lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' ) _lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze() _lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() _lowerCamelCase : Any = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : str ): """simple docstring""" return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()] def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] ) _lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) _lowerCamelCase : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer.pad_token_id ) _lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch lowerCAmelCase__ = getLogger(__name__) def snake_case_ ( A_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(A_ ) ) def snake_case_ ( A_ : str ): '''simple docstring''' _lowerCamelCase : Dict = get_git_info() save_json(A_, os.path.join(A_, '''git_log.json''' ) ) def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ): '''simple docstring''' with open(A_, '''w''' ) as f: json.dump(A_, A_, indent=A_, **A_ ) def snake_case_ ( A_ : Any ): '''simple docstring''' with open(A_ ) as f: return json.load(A_ ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ ) _lowerCamelCase : str = { '''repo_id''': str(A_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def snake_case_ ( A_ : Callable, A_ : Iterable ): '''simple docstring''' return list(map(A_, A_ ) ) def snake_case_ ( A_ : str, A_ : Tuple ): '''simple docstring''' with open(A_, '''wb''' ) as f: return pickle.dump(A_, A_ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' def remove_articles(A_ : str ): return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ ) def white_space_fix(A_ : Any ): return " ".join(text.split() ) def remove_punc(A_ : List[Any] ): _lowerCamelCase : Any = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case_ ( A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : str = normalize_answer(A_ ).split() _lowerCamelCase : int = normalize_answer(A_ ).split() _lowerCamelCase : str = Counter(A_ ) & Counter(A_ ) _lowerCamelCase : Any = sum(common.values() ) if num_same == 0: return 0 _lowerCamelCase : int = 1.0 * num_same / len(A_ ) _lowerCamelCase : str = 1.0 * num_same / len(A_ ) _lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case_ ( A_ : Dict, A_ : str ): '''simple docstring''' return normalize_answer(A_ ) == normalize_answer(A_ ) def snake_case_ ( A_ : List[str], A_ : List[str] ): '''simple docstring''' assert len(A_ ) == len(A_ ) _lowerCamelCase : Optional[Any] = 0 for hypo, pred in zip(A_, A_ ): em += exact_match_score(A_, A_ ) if len(A_ ) > 0: em /= len(A_ ) return {"em": em} def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Dict = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _lowerCamelCase : Tuple = '''dropout_rate''' for p in extra_params: if getattr(A_, A_, A_ ): if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) ) delattr(A_, A_ ) continue _lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p] setattr(A_, A_, getattr(A_, A_ ) ) delattr(A_, A_ ) return hparams, config
83
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowerCAmelCase__ = '''<<<<<<< This should probably be modified because it mentions: ''' lowerCAmelCase__ = '''======= >>>>>>> ''' lowerCAmelCase__ = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] lowerCAmelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def snake_case_ ( A_ : Namespace ): '''simple docstring''' return ConvertCommand(args.tfds_path, args.datasets_directory ) class __snake_case ( _lowercase): @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : ArgumentParser ): """simple docstring""" _lowerCamelCase : List[str] = parser.add_parser( '''convert''' , help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.''' , ) train_parser.add_argument( '''--tfds_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.''' , ) train_parser.add_argument( '''--datasets_directory''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the HuggingFace Datasets folder.''' ) train_parser.set_defaults(func=__lowerCAmelCase ) def __init__( self : str , __lowerCAmelCase : str , __lowerCAmelCase : str , *__lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = get_logger('''datasets-cli/converting''' ) _lowerCamelCase : int = tfds_path _lowerCamelCase : Dict = datasets_directory def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if os.path.isdir(self._tfds_path ): _lowerCamelCase : Union[str, Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): _lowerCamelCase : Dict = os.path.dirname(self._tfds_path ) else: raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.''' ) _lowerCamelCase : int = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) _lowerCamelCase : str = [] _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Union[str, Any] = {} if os.path.isdir(self._tfds_path ): _lowerCamelCase : List[str] = os.listdir(__lowerCAmelCase ) else: _lowerCamelCase : Optional[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) _lowerCamelCase : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not os.path.isfile(__lowerCAmelCase ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('''Skipping file''' ) continue with open(__lowerCAmelCase , encoding='''utf-8''' ) as f: _lowerCamelCase : Tuple = f.readlines() _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Union[str, Any] = False _lowerCamelCase : int = False _lowerCamelCase : Tuple = [] for line in lines: _lowerCamelCase : Optional[int] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: _lowerCamelCase : Union[str, Any] = '''import datasets\n''' elif "import tensorflow" in out_line: # order is important here _lowerCamelCase : List[str] = '''''' continue elif "from absl import logging" in out_line: _lowerCamelCase : str = '''from datasets import logging\n''' elif "getLogger" in out_line: _lowerCamelCase : Union[str, Any] = out_line.replace('''getLogger''' , '''get_logger''' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): _lowerCamelCase : Dict = True _lowerCamelCase : Optional[int] = list(filter(lambda __lowerCAmelCase : e in out_line , __lowerCAmelCase ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(__lowerCAmelCase ) + '''\n''' ) out_lines.append(__lowerCAmelCase ) out_lines.append(__lowerCAmelCase ) continue else: for pattern, replacement in TO_CONVERT: _lowerCamelCase : str = re.sub(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: _lowerCamelCase : Dict = re.match(R'''from\stensorflow_datasets.*import\s([^\.\r\n]+)''' , __lowerCAmelCase ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(''',''' ) ) _lowerCamelCase : Union[str, Any] = '''from . import ''' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: _lowerCamelCase : Any = True out_lines.append(__lowerCAmelCase ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset _lowerCamelCase : Union[str, Any] = f_name.replace('''.py''' , '''''' ) _lowerCamelCase : List[str] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(__lowerCAmelCase ) if needs_manual_update: with_manual_update.append(__lowerCAmelCase ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.writelines(__lowerCAmelCase ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: _lowerCamelCase : Optional[int] = os.path.basename(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = imports_to_builder_map[f_name.replace('''.py''' , '''''' )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(__lowerCAmelCase , __lowerCAmelCase ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
83
1
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) _lowerCamelCase : str = str(bin(A_ ) ) binary_number += "0" * shift_amount return binary_number def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) _lowerCamelCase : Any = str(bin(A_ ) )[2:] if shift_amount >= len(A_ ): return "0b0" _lowerCamelCase : int = binary_number[: len(A_ ) - shift_amount] return "0b" + shifted_binary_number def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' if number >= 0: # Get binary representation of positive number _lowerCamelCase : Any = '''0''' + str(bin(A_ ) ).strip('''-''' )[2:] else: # Get binary (2's complement) representation of negative number _lowerCamelCase : Any = len(bin(A_ )[3:] ) # Find 2's complement of number _lowerCamelCase : Optional[Any] = bin(abs(A_ ) - (1 << binary_number_length) )[3:] _lowerCamelCase : Tuple = ( '''1''' + '''0''' * (binary_number_length - len(A_ )) + binary_number ) if shift_amount >= len(A_ ): return "0b" + binary_number[0] * len(A_ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(A_ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
83
"""simple docstring""" def snake_case_ ( A_ : list, A_ : list, A_ : int, A_ : int, A_ : int ): '''simple docstring''' if index == number_of_items: return 0 _lowerCamelCase : int = 0 _lowerCamelCase : str = 0 _lowerCamelCase : Dict = knapsack(A_, A_, A_, A_, index + 1 ) if weights[index] <= max_weight: _lowerCamelCase : Tuple = values[index] + knapsack( A_, A_, A_, max_weight - weights[index], index + 1 ) return max(A_, A_ ) if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class __snake_case ( _lowercase): snake_case__ : Optional[Any] = "biogpt" def __init__( self : Any , __lowerCAmelCase : Tuple=4_2_3_8_4 , __lowerCAmelCase : Union[str, Any]=1_0_2_4 , __lowerCAmelCase : Optional[int]=2_4 , __lowerCAmelCase : Optional[Any]=1_6 , __lowerCAmelCase : Optional[Any]=4_0_9_6 , __lowerCAmelCase : Any="gelu" , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : str=1_0_2_4 , __lowerCAmelCase : Optional[Any]=0.02 , __lowerCAmelCase : Dict=1E-12 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Dict=True , __lowerCAmelCase : Tuple=0.0 , __lowerCAmelCase : int=0.0 , __lowerCAmelCase : Tuple=1 , __lowerCAmelCase : List[str]=0 , __lowerCAmelCase : Tuple=2 , **__lowerCAmelCase : Tuple , ): """simple docstring""" _lowerCamelCase : Dict = vocab_size _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : List[str] = hidden_size _lowerCamelCase : Any = num_hidden_layers _lowerCamelCase : List[Any] = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : Dict = hidden_act _lowerCamelCase : Optional[int] = hidden_dropout_prob _lowerCamelCase : Optional[int] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = initializer_range _lowerCamelCase : str = layer_norm_eps _lowerCamelCase : Optional[int] = scale_embedding _lowerCamelCase : Dict = use_cache _lowerCamelCase : Any = layerdrop _lowerCamelCase : Tuple = activation_dropout super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase )
83
"""simple docstring""" from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=_lowercase): snake_case__ : Optional[Any] = ["transformers", "torch", "note_seq"] def __init__( self : Union[str, Any] , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : List[Any] ): """simple docstring""" requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , *__lowerCAmelCase : str , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls : int , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[Any] ): """simple docstring""" requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
83
1
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowerCAmelCase__ = '''<<<<<<< This should probably be modified because it mentions: ''' lowerCAmelCase__ = '''======= >>>>>>> ''' lowerCAmelCase__ = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] lowerCAmelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def snake_case_ ( A_ : Namespace ): '''simple docstring''' return ConvertCommand(args.tfds_path, args.datasets_directory ) class __snake_case ( _lowercase): @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : ArgumentParser ): """simple docstring""" _lowerCamelCase : List[str] = parser.add_parser( '''convert''' , help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.''' , ) train_parser.add_argument( '''--tfds_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.''' , ) train_parser.add_argument( '''--datasets_directory''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the HuggingFace Datasets folder.''' ) train_parser.set_defaults(func=__lowerCAmelCase ) def __init__( self : str , __lowerCAmelCase : str , __lowerCAmelCase : str , *__lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = get_logger('''datasets-cli/converting''' ) _lowerCamelCase : int = tfds_path _lowerCamelCase : Dict = datasets_directory def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if os.path.isdir(self._tfds_path ): _lowerCamelCase : Union[str, Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): _lowerCamelCase : Dict = os.path.dirname(self._tfds_path ) else: raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.''' ) _lowerCamelCase : int = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) _lowerCamelCase : str = [] _lowerCamelCase : Union[str, Any] = [] _lowerCamelCase : Union[str, Any] = {} if os.path.isdir(self._tfds_path ): _lowerCamelCase : List[str] = os.listdir(__lowerCAmelCase ) else: _lowerCamelCase : Optional[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) _lowerCamelCase : Union[str, Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) if not os.path.isfile(__lowerCAmelCase ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('''Skipping file''' ) continue with open(__lowerCAmelCase , encoding='''utf-8''' ) as f: _lowerCamelCase : Tuple = f.readlines() _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Union[str, Any] = False _lowerCamelCase : int = False _lowerCamelCase : Tuple = [] for line in lines: _lowerCamelCase : Optional[int] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: _lowerCamelCase : Union[str, Any] = '''import datasets\n''' elif "import tensorflow" in out_line: # order is important here _lowerCamelCase : List[str] = '''''' continue elif "from absl import logging" in out_line: _lowerCamelCase : str = '''from datasets import logging\n''' elif "getLogger" in out_line: _lowerCamelCase : Union[str, Any] = out_line.replace('''getLogger''' , '''get_logger''' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): _lowerCamelCase : Dict = True _lowerCamelCase : Optional[int] = list(filter(lambda __lowerCAmelCase : e in out_line , __lowerCAmelCase ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(__lowerCAmelCase ) + '''\n''' ) out_lines.append(__lowerCAmelCase ) out_lines.append(__lowerCAmelCase ) continue else: for pattern, replacement in TO_CONVERT: _lowerCamelCase : str = re.sub(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: _lowerCamelCase : Dict = re.match(R'''from\stensorflow_datasets.*import\s([^\.\r\n]+)''' , __lowerCAmelCase ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(''',''' ) ) _lowerCamelCase : Union[str, Any] = '''from . import ''' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: _lowerCamelCase : Any = True out_lines.append(__lowerCAmelCase ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset _lowerCamelCase : Union[str, Any] = f_name.replace('''.py''' , '''''' ) _lowerCamelCase : List[str] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase , __lowerCAmelCase ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(__lowerCAmelCase ) if needs_manual_update: with_manual_update.append(__lowerCAmelCase ) with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.writelines(__lowerCAmelCase ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: _lowerCamelCase : Optional[int] = os.path.basename(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = imports_to_builder_map[f_name.replace('''.py''' , '''''' )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(__lowerCAmelCase , __lowerCAmelCase ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
83
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __snake_case ( unittest.TestCase): @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Any = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _lowerCamelCase : Union[str, Any] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids _lowerCamelCase : Optional[int] = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids _lowerCamelCase : List[Any] = shift_tokens_right(__lowerCAmelCase , model.config.pad_token_id , model.config.decoder_start_token_id ) _lowerCamelCase : int = model(__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase ).logits _lowerCamelCase : Optional[Any] = optax.softmax_cross_entropy(__lowerCAmelCase , onehot(__lowerCAmelCase , logits.shape[-1] ) ).mean() _lowerCamelCase : Dict = -(labels.shape[-1] * loss.item()) _lowerCamelCase : Dict = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
83
1
"""simple docstring""" import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCAmelCase__ = 256 class __snake_case ( _lowercase): snake_case__ : Optional[Any] = ["melgan"] def __init__( self : List[Any] , __lowerCAmelCase : SpectrogramNotesEncoder , __lowerCAmelCase : SpectrogramContEncoder , __lowerCAmelCase : TaFilmDecoder , __lowerCAmelCase : DDPMScheduler , __lowerCAmelCase : OnnxRuntimeModel if is_onnx_available() else Any , ): """simple docstring""" super().__init__() # From MELGAN _lowerCamelCase : Tuple = math.log(1E-5 ) # Matches MelGAN training. _lowerCamelCase : Optional[Any] = 4.0 # Largest value for most examples _lowerCamelCase : Tuple = 1_2_8 self.register_modules( notes_encoder=__lowerCAmelCase , continuous_encoder=__lowerCAmelCase , decoder=__lowerCAmelCase , scheduler=__lowerCAmelCase , melgan=__lowerCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any]=(-1.0, 1.0) , __lowerCAmelCase : Union[str, Any]=False ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Dict = output_range if clip: _lowerCamelCase : Union[str, Any] = torch.clip(__lowerCAmelCase , self.min_value , self.max_value ) # Scale to [0, 1]. _lowerCamelCase : List[Any] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any]=(-1.0, 1.0) , __lowerCAmelCase : Optional[int]=False ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Union[str, Any] = input_range _lowerCamelCase : int = torch.clip(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if clip else outputs # Scale to [0, 1]. _lowerCamelCase : Dict = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : Any = input_tokens > 0 _lowerCamelCase , _lowerCamelCase : Optional[int] = self.notes_encoder( encoder_input_tokens=__lowerCAmelCase , encoder_inputs_mask=__lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : str = self.continuous_encoder( encoder_inputs=__lowerCAmelCase , encoder_inputs_mask=__lowerCAmelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : List[str] = noise_time if not torch.is_tensor(__lowerCAmelCase ): _lowerCamelCase : Optional[int] = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(__lowerCAmelCase ) and len(timesteps.shape ) == 0: _lowerCamelCase : Any = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _lowerCamelCase : List[Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) _lowerCamelCase : Dict = self.decoder( encodings_and_masks=__lowerCAmelCase , decoder_input_tokens=__lowerCAmelCase , decoder_noise_time=__lowerCAmelCase ) return logits @torch.no_grad() def __call__( self : str , __lowerCAmelCase : List[List[int]] , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : int = 1_0_0 , __lowerCAmelCase : bool = True , __lowerCAmelCase : str = "numpy" , __lowerCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowerCAmelCase : int = 1 , ): """simple docstring""" if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(__lowerCAmelCase )}.''' ) _lowerCamelCase : List[Any] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) _lowerCamelCase : Dict = np.zeros([1, 0, self.n_dims] , np.floataa ) _lowerCamelCase : Optional[Any] = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=__lowerCAmelCase , device=self.device ) for i, encoder_input_tokens in enumerate(__lowerCAmelCase ): if i == 0: _lowerCamelCase : Optional[int] = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. _lowerCamelCase : Optional[Any] = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=__lowerCAmelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. _lowerCamelCase : str = ones _lowerCamelCase : Union[str, Any] = self.scale_features( __lowerCAmelCase , output_range=[-1.0, 1.0] , clip=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=__lowerCAmelCase , continuous_mask=__lowerCAmelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop _lowerCamelCase : Union[str, Any] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=__lowerCAmelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(__lowerCAmelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): _lowerCamelCase : Tuple = self.decode( encodings_and_masks=__lowerCAmelCase , input_tokens=__lowerCAmelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 _lowerCamelCase : Union[str, Any] = self.scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample _lowerCamelCase : Optional[int] = self.scale_to_features(__lowerCAmelCase , input_range=[-1.0, 1.0] ) _lowerCamelCase : Union[str, Any] = mel[:1] _lowerCamelCase : int = mel.cpu().float().numpy() _lowerCamelCase : Optional[int] = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__lowerCAmelCase , __lowerCAmelCase ) logger.info('''Generated segment''' , __lowerCAmelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( '''Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.''' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( '''Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.''' ) if output_type == "numpy": _lowerCamelCase : Union[str, Any] = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: _lowerCamelCase : str = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=__lowerCAmelCase )
83
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''', [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ], ) def snake_case_ ( A_ : Dict, A_ : List[str] ): '''simple docstring''' _lowerCamelCase : int = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''', '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''', '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) _lowerCamelCase : str = DatasetInfosDict.from_directory(A_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''', [ DatasetInfo(), DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ), ], ) def snake_case_ ( A_ : str, A_ : DatasetInfo ): '''simple docstring''' _lowerCamelCase : Optional[Any] = str(A_ ) dataset_info.write_to_directory(A_ ) _lowerCamelCase : str = DatasetInfo.from_directory(A_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(A_, '''dataset_info.json''' ) ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = DatasetInfo( description='''foo''', citation='''bar''', homepage='''https://foo.bar''', license='''CC0''', features=Features({'''a''': Value('''int32''' )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train''', '''num_examples''': 42}], download_checksums={}, download_size=13_37, post_processing_size=4_42, dataset_size=12_34, size_in_bytes=13_37 + 4_42 + 12_34, ) _lowerCamelCase : Optional[Any] = dataset_info._to_yaml_dict() assert sorted(A_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) ) _lowerCamelCase : str = yaml.safe_dump(A_ ) _lowerCamelCase : Tuple = yaml.safe_load(A_ ) assert dataset_info_yaml_dict == reloaded def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : int = DatasetInfo() _lowerCamelCase : Dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''', [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''', features=Features({'''a''': Value('''int32''' )} ), builder_name='''builder''', config_name='''config''', version='''1.0.0''', splits=[{'''name''': '''train'''}], download_size=42, ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=13_37 ), } ), ], ) def snake_case_ ( A_ : Optional[Any], A_ : DatasetInfosDict ): '''simple docstring''' _lowerCamelCase : List[str] = str(A_ ) dataset_infos_dict.write_to_directory(A_ ) _lowerCamelCase : List[Any] = DatasetInfosDict.from_directory(A_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _lowerCamelCase : str = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _lowerCamelCase : Any = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(A_, '''README.md''' ) )
83
1
"""simple docstring""" import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch lowerCAmelCase__ = '''sshleifer/bart-tiny-random''' lowerCAmelCase__ = '''patrickvonplaten/t5-tiny-random''' @require_torch class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return AutoConfig.from_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase , *_lowerCamelCase : Optional[Any] = create_student_by_copying_alternating_layers(__lowerCAmelCase , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase , *_lowerCamelCase : Union[str, Any] = create_student_by_copying_alternating_layers(__lowerCAmelCase , tempfile.mkdtemp() , e=1 , d=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase , *_lowerCamelCase : Dict = create_student_by_copying_alternating_layers(__lowerCAmelCase , tempfile.mkdtemp() , e=1 , d=__lowerCAmelCase ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase , *_lowerCamelCase : str = create_student_by_copying_alternating_layers(__lowerCAmelCase , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" with self.assertRaises(__lowerCAmelCase ): create_student_by_copying_alternating_layers(__lowerCAmelCase , tempfile.mkdtemp() , e=__lowerCAmelCase , d=__lowerCAmelCase )
83
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __snake_case : def __init__( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : List[str]=2_4 , __lowerCAmelCase : str=1_6 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : int=4 , __lowerCAmelCase : int=3_7 , __lowerCAmelCase : Union[str, Any]="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : int=1_0 , __lowerCAmelCase : List[Any]=0.02 , __lowerCAmelCase : str=None , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Union[str, Any]=2 , ): """simple docstring""" _lowerCamelCase : List[str] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : Tuple = patch_size _lowerCamelCase : Optional[int] = max_length _lowerCamelCase : List[Any] = num_mel_bins _lowerCamelCase : int = is_training _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : Dict = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : List[str] = scope _lowerCamelCase : Optional[int] = frequency_stride _lowerCamelCase : List[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _lowerCamelCase : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _lowerCamelCase : Union[str, Any] = (self.max_length - self.patch_size) // self.time_stride + 1 _lowerCamelCase : Any = frequency_out_dimension * time_out_dimension _lowerCamelCase : List[Any] = num_patches + 2 def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Optional[int] = self.get_config() return config, input_values, labels def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : List[Any] = ASTModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Optional[Any] = config_and_inputs _lowerCamelCase : int = {'''input_values''': input_values} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Any = False snake_case__ : List[Any] = False snake_case__ : Optional[Any] = False snake_case__ : Optional[Any] = False def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[int] = ASTModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCamelCase : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : str = ['''input_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Union[str, Any] = ASTModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : List[str] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' ) _lowerCamelCase , _lowerCamelCase : str = torchaudio.load(A_ ) return audio, sampling_rate @require_torch @require_torchaudio class __snake_case ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = self.default_feature_extractor _lowerCamelCase : Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = self.default_feature_extractor _lowerCamelCase , _lowerCamelCase : List[Any] = prepare_audio() _lowerCamelCase : Dict = audio.squeeze().numpy() _lowerCamelCase : Tuple = feature_extractor(__lowerCAmelCase , sampling_rate=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _lowerCamelCase : Tuple = model(**__lowerCAmelCase ) # verify the logits _lowerCamelCase : Tuple = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _lowerCamelCase : Optional[int] = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
83
1
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCAmelCase__ = logging.get_logger(__name__) class __snake_case : def __init__( self : str , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = question_encoder _lowerCamelCase : Any = generator _lowerCamelCase : List[str] = self.question_encoder def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : int ): """simple docstring""" if os.path.isfile(__lowerCAmelCase ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase ) _lowerCamelCase : Tuple = os.path.join(__lowerCAmelCase , '''question_encoder_tokenizer''' ) _lowerCamelCase : List[Any] = os.path.join(__lowerCAmelCase , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(__lowerCAmelCase ) self.generator.save_pretrained(__lowerCAmelCase ) @classmethod def SCREAMING_SNAKE_CASE ( cls : Optional[Any] , __lowerCAmelCase : Optional[int] , **__lowerCAmelCase : Any ): """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer _lowerCamelCase : Dict = kwargs.pop('''config''' , __lowerCAmelCase ) if config is None: _lowerCamelCase : Any = RagConfig.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : int = AutoTokenizer.from_pretrained( __lowerCAmelCase , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) _lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained( __lowerCAmelCase , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=__lowerCAmelCase , generator=__lowerCAmelCase ) def __call__( self : Any , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : Tuple ): """simple docstring""" return self.current_tokenizer(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : Tuple ): """simple docstring""" return self.generator.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple , *__lowerCAmelCase : Any , **__lowerCAmelCase : List[Any] ): """simple docstring""" return self.generator.decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.question_encoder def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.generator def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[List[str]] = None , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : str = "longest" , __lowerCAmelCase : str = None , __lowerCAmelCase : bool = True , **__lowerCAmelCase : int , ): """simple docstring""" warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , __lowerCAmelCase , ) if max_length is None: _lowerCamelCase : Tuple = self.current_tokenizer.model_max_length _lowerCamelCase : str = self( __lowerCAmelCase , add_special_tokens=__lowerCAmelCase , return_tensors=__lowerCAmelCase , max_length=__lowerCAmelCase , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , **__lowerCAmelCase , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: _lowerCamelCase : Tuple = self.current_tokenizer.model_max_length _lowerCamelCase : Optional[int] = self( text_target=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , return_tensors=__lowerCAmelCase , padding=__lowerCAmelCase , max_length=__lowerCAmelCase , truncation=__lowerCAmelCase , **__lowerCAmelCase , ) _lowerCamelCase : Dict = labels['''input_ids'''] return model_inputs
83
"""simple docstring""" import math import random from typing import Any from .hill_climbing import SearchProblem def snake_case_ ( A_ : Dict, A_ : bool = True, A_ : float = math.inf, A_ : float = -math.inf, A_ : float = math.inf, A_ : float = -math.inf, A_ : bool = False, A_ : float = 1_00, A_ : float = 0.01, A_ : float = 1, ): '''simple docstring''' _lowerCamelCase : Optional[int] = False _lowerCamelCase : str = search_prob _lowerCamelCase : str = start_temperate _lowerCamelCase : Optional[Any] = [] _lowerCamelCase : int = 0 _lowerCamelCase : Any = None while not search_end: _lowerCamelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCamelCase : Tuple = current_state scores.append(A_ ) iterations += 1 _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCamelCase : List[Any] = random.randint(0, len(A_ ) - 1 ) # picking a random neighbor _lowerCamelCase : Dict = neighbors.pop(A_ ) _lowerCamelCase : Union[str, Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCamelCase : Optional[Any] = picked_neighbor else: _lowerCamelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCamelCase : Union[str, Any] = picked_neighbor _lowerCamelCase : List[str] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCamelCase : Tuple = True else: _lowerCamelCase : Optional[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(A_ ), A_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowerCAmelCase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def snake_case_ ( A_ : Optional[int], A_ : List[Any] ): '''simple docstring''' return (3 * x**2) - (6 * y) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) lowerCAmelCase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowerCAmelCase__ = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
83
1
"""simple docstring""" def snake_case_ ( A_ : List[str] ): '''simple docstring''' _lowerCamelCase : Tuple = 0 _lowerCamelCase : Union[str, Any] = len(A_ ) for i in range(n - 1 ): for j in range(i + 1, A_ ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def snake_case_ ( A_ : List[str] ): '''simple docstring''' if len(A_ ) <= 1: return arr, 0 _lowerCamelCase : int = len(A_ ) // 2 _lowerCamelCase : int = arr[0:mid] _lowerCamelCase : int = arr[mid:] _lowerCamelCase , _lowerCamelCase : str = count_inversions_recursive(A_ ) _lowerCamelCase , _lowerCamelCase : int = count_inversions_recursive(A_ ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = _count_cross_inversions(A_, A_ ) _lowerCamelCase : Optional[Any] = inversion_p + inversions_q + cross_inversions return c, num_inversions def snake_case_ ( A_ : int, A_ : Dict ): '''simple docstring''' _lowerCamelCase : Tuple = [] _lowerCamelCase : List[str] = 0 while i < len(A_ ) and j < len(A_ ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(A_ ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(A_ ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Tuple = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) _lowerCamelCase : List[str] = count_inversions_bf(A_ ) _lowerCamelCase , _lowerCamelCase : List[str] = count_inversions_recursive(A_ ) assert num_inversions_bf == num_inversions_recursive == 8 print('''number of inversions = ''', A_ ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() _lowerCamelCase : List[Any] = count_inversions_bf(A_ ) _lowerCamelCase , _lowerCamelCase : List[Any] = count_inversions_recursive(A_ ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''', A_ ) # an empty list should also have zero inversions _lowerCamelCase : str = [] _lowerCamelCase : Optional[int] = count_inversions_bf(A_ ) _lowerCamelCase , _lowerCamelCase : Any = count_inversions_recursive(A_ ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''', A_ ) if __name__ == "__main__": main()
83
"""simple docstring""" from collections import namedtuple lowerCAmelCase__ = namedtuple('''from_to''', '''from_ to''') lowerCAmelCase__ = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def snake_case_ ( A_ : float, A_ : str, A_ : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ''', '''.join(A_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ''', '''.join(A_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __snake_case ( _lowercase): snake_case__ : Any = (DDPMScheduler,) def SCREAMING_SNAKE_CASE ( self : str , **__lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**__lowerCAmelCase ) return config def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__lowerCAmelCase , beta_end=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self.check_over_configs(thresholding=__lowerCAmelCase ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=__lowerCAmelCase , prediction_type=__lowerCAmelCase , sample_max_value=__lowerCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Tuple = self.scheduler_classes[0] _lowerCamelCase : int = self.get_scheduler_config() _lowerCamelCase : Any = scheduler_class(**__lowerCAmelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.0_09_79 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1E-5 def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : str = self.scheduler_classes[0] _lowerCamelCase : List[Any] = self.get_scheduler_config() _lowerCamelCase : Optional[int] = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : Tuple = len(__lowerCAmelCase ) _lowerCamelCase : Dict = self.dummy_model() _lowerCamelCase : str = self.dummy_sample_deter _lowerCamelCase : Any = torch.manual_seed(0 ) for t in reversed(range(__lowerCAmelCase ) ): # 1. predict noise residual _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , __lowerCAmelCase ) # 2. predict previous mean of sample x_t-1 _lowerCamelCase : Dict = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _lowerCamelCase : Dict = pred_prev_sample _lowerCamelCase : str = torch.sum(torch.abs(__lowerCAmelCase ) ) _lowerCamelCase : str = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 2_58.96_06 ) < 1E-2 assert abs(result_mean.item() - 0.33_72 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[str] = self.scheduler_classes[0] _lowerCamelCase : Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _lowerCamelCase : Union[str, Any] = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : Dict = len(__lowerCAmelCase ) _lowerCamelCase : str = self.dummy_model() _lowerCamelCase : Optional[Any] = self.dummy_sample_deter _lowerCamelCase : Dict = torch.manual_seed(0 ) for t in reversed(range(__lowerCAmelCase ) ): # 1. predict noise residual _lowerCamelCase : Union[str, Any] = model(__lowerCAmelCase , __lowerCAmelCase ) # 2. predict previous mean of sample x_t-1 _lowerCamelCase : List[Any] = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _lowerCamelCase : Any = pred_prev_sample _lowerCamelCase : List[str] = torch.sum(torch.abs(__lowerCAmelCase ) ) _lowerCamelCase : str = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 2_02.02_96 ) < 1E-2 assert abs(result_mean.item() - 0.26_31 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : List[str] = self.scheduler_classes[0] _lowerCamelCase : List[str] = self.get_scheduler_config() _lowerCamelCase : Dict = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : List[str] = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = scheduler.timesteps for i, timestep in enumerate(__lowerCAmelCase ): if i == len(__lowerCAmelCase ) - 1: _lowerCamelCase : str = -1 else: _lowerCamelCase : List[Any] = timesteps[i + 1] _lowerCamelCase : Optional[int] = scheduler.previous_timestep(__lowerCAmelCase ) _lowerCamelCase : Tuple = prev_t.item() self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : str = self.scheduler_classes[0] _lowerCamelCase : Optional[int] = self.get_scheduler_config() _lowerCamelCase : str = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : Any = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(__lowerCAmelCase , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Tuple = self.scheduler_classes[0] _lowerCamelCase : Optional[Any] = self.get_scheduler_config() _lowerCamelCase : List[str] = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : List[Any] = [1_0_0, 8_7, 5_0, 1, 0] _lowerCamelCase : List[str] = len(__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=__lowerCAmelCase , timesteps=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.scheduler_classes[0] _lowerCamelCase : str = self.get_scheduler_config() _lowerCamelCase : Optional[Any] = scheduler_class(**__lowerCAmelCase ) _lowerCamelCase : int = [scheduler.config.num_train_timesteps] with self.assertRaises( __lowerCAmelCase , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=__lowerCAmelCase )
83
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case ( _lowercase): def __init__( self : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : List[str]=9_9 , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : Union[str, Any]=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : Optional[int]=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : int=5_1_2 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any="None" , __lowerCAmelCase : str=3 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[Any]=None , ): """simple docstring""" _lowerCamelCase : Dict = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Dict = use_input_mask _lowerCamelCase : Tuple = use_token_type_ids _lowerCamelCase : Optional[Any] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : str = type_vocab_size _lowerCamelCase : List[Any] = type_sequence_label_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Optional[int] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : int = relative_attention _lowerCamelCase : Union[str, Any] = position_biased_input _lowerCamelCase : str = pos_att_type _lowerCamelCase : Tuple = scope def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : int = None _lowerCamelCase : Union[str, Any] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : str = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )[0] _lowerCamelCase : List[Any] = model(__lowerCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : Dict = DebertaVaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.num_labels _lowerCamelCase : Tuple = DebertaVaForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = DebertaVaForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Union[str, Any] = config_and_inputs _lowerCamelCase : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : int = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : int = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = True snake_case__ : List[Any] = False snake_case__ : int = False snake_case__ : Optional[Any] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[str] = DebertaVaModelTester(self ) _lowerCamelCase : Any = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) _lowerCamelCase : List[str] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowerCamelCase : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0] # compare the actual values for a slice. _lowerCamelCase : Union[str, Any] = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowerCAmelCase , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
83
1
"""simple docstring""" from typing import Any import numpy as np def snake_case_ ( A_ : np.ndarray ): '''simple docstring''' return np.array_equal(A_, matrix.conjugate().T ) def snake_case_ ( A_ : np.ndarray, A_ : np.ndarray ): '''simple docstring''' _lowerCamelCase : Any = v.conjugate().T _lowerCamelCase : List[Any] = v_star.dot(A_ ) assert isinstance(A_, np.ndarray ) return (v_star_dot.dot(A_ )) / (v_star.dot(A_ )) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Dict = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) _lowerCamelCase : List[Any] = np.array([[1], [2], [3]] ) assert is_hermitian(A_ ), F'''{a} is not hermitian.''' print(rayleigh_quotient(A_, A_ ) ) _lowerCamelCase : List[str] = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(A_ ), F'''{a} is not hermitian.''' assert rayleigh_quotient(A_, A_ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
83
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = '''hf-internal-testing/tiny-random-bert''' lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''') lowerCAmelCase__ = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6''' class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[Any] = cached_file(__lowerCAmelCase , __lowerCAmelCase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__lowerCAmelCase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__lowerCAmelCase , __lowerCAmelCase ) ) ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : Optional[int] = f.read() self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) self.assertTrue(os.path.isfile(__lowerCAmelCase ) ) # File is cached at the same place the second time. _lowerCamelCase : Tuple = cached_file(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Using a specific revision to test the full commit hash. _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''9b8c223''' ) self.assertEqual(__lowerCAmelCase , os.path.join(__lowerCAmelCase , '''snapshots''' , __lowerCAmelCase , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): _lowerCamelCase : Optional[int] = cached_file('''tiny-random-bert''' , __lowerCAmelCase ) with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): _lowerCamelCase : str = cached_file(__lowerCAmelCase , __lowerCAmelCase , revision='''aaaa''' ) with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : int = cached_file(__lowerCAmelCase , '''conf''' ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex(__lowerCAmelCase , '''does not appear to have a file named''' ): _lowerCamelCase : Dict = cached_file(__lowerCAmelCase , '''conf''' ) with open(os.path.join(__lowerCAmelCase , '''refs''' , '''main''' ) ) as f: _lowerCamelCase : List[Any] = f.read() self.assertTrue(os.path.isfile(os.path.join(__lowerCAmelCase , '''.no_exist''' , __lowerCAmelCase , '''conf''' ) ) ) _lowerCamelCase : str = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = cached_file(__lowerCAmelCase , '''conf''' , local_files_only=__lowerCAmelCase , _raise_exceptions_for_missing_entries=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) _lowerCamelCase : Any = mock.Mock() _lowerCamelCase : Optional[Any] = 5_0_0 _lowerCamelCase : Dict = {} _lowerCamelCase : List[Any] = HTTPError _lowerCamelCase : int = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__lowerCAmelCase ) as mock_head: _lowerCamelCase : Union[str, Any] = cached_file(__lowerCAmelCase , '''conf''' , _raise_exceptions_for_connection_errors=__lowerCAmelCase ) self.assertIsNone(__lowerCAmelCase ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __lowerCAmelCase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__lowerCAmelCase , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase , revision='''ahaha''' ) _lowerCamelCase : Dict = get_file_from_repo('''bert-base-cased''' , __lowerCAmelCase ) # The name is the cached name which is not very easy to test, so instead we load the content. _lowerCamelCase : Dict = json.loads(open(__lowerCAmelCase , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = Path(__lowerCAmelCase ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__lowerCAmelCase , '''a.txt''' ) , str(__lowerCAmelCase ) ) self.assertIsNone(get_file_from_repo(__lowerCAmelCase , '''b.txt''' ) )
83
1
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[int] = "xlm-prophetnet" snake_case__ : List[Any] = ["past_key_values"] snake_case__ : Any = { "num_attention_heads": "num_encoder_attention_heads", } def __init__( self : int , __lowerCAmelCase : Optional[float] = 0.1 , __lowerCAmelCase : Optional[Union[str, Callable]] = "gelu" , __lowerCAmelCase : Optional[int] = 3_0_5_2_2 , __lowerCAmelCase : Optional[int] = 1_0_2_4 , __lowerCAmelCase : Optional[int] = 4_0_9_6 , __lowerCAmelCase : Optional[int] = 1_2 , __lowerCAmelCase : Optional[int] = 1_6 , __lowerCAmelCase : Optional[int] = 4_0_9_6 , __lowerCAmelCase : Optional[int] = 1_2 , __lowerCAmelCase : Optional[int] = 1_6 , __lowerCAmelCase : Optional[float] = 0.1 , __lowerCAmelCase : Optional[float] = 0.1 , __lowerCAmelCase : Optional[int] = 5_1_2 , __lowerCAmelCase : Optional[float] = 0.02 , __lowerCAmelCase : Optional[bool] = True , __lowerCAmelCase : Optional[bool] = True , __lowerCAmelCase : Optional[int] = 0 , __lowerCAmelCase : Optional[int] = 2 , __lowerCAmelCase : Optional[int] = 3_2 , __lowerCAmelCase : Optional[int] = 1_2_8 , __lowerCAmelCase : Optional[bool] = False , __lowerCAmelCase : Optional[float] = 0.0 , __lowerCAmelCase : Optional[bool] = True , __lowerCAmelCase : Optional[int] = 0 , __lowerCAmelCase : Optional[int] = 1 , __lowerCAmelCase : Optional[int] = 2 , **__lowerCAmelCase : List[Any] , ): """simple docstring""" _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : Optional[int] = hidden_size _lowerCamelCase : str = encoder_ffn_dim _lowerCamelCase : int = num_encoder_layers _lowerCamelCase : Optional[Any] = num_encoder_attention_heads _lowerCamelCase : Union[str, Any] = decoder_ffn_dim _lowerCamelCase : Optional[Any] = num_decoder_layers _lowerCamelCase : Optional[Any] = num_decoder_attention_heads _lowerCamelCase : Union[str, Any] = max_position_embeddings _lowerCamelCase : List[Any] = init_std # Normal(0, this parameter) _lowerCamelCase : List[str] = activation_function # parameters for xlmprophetnet _lowerCamelCase : Optional[Any] = ngram _lowerCamelCase : Any = num_buckets _lowerCamelCase : int = relative_max_distance _lowerCamelCase : Union[str, Any] = disable_ngram_loss _lowerCamelCase : Dict = eps # 3 Types of Dropout _lowerCamelCase : Union[str, Any] = attention_dropout _lowerCamelCase : str = activation_dropout _lowerCamelCase : int = dropout _lowerCamelCase : Any = use_cache super().__init__( pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , is_encoder_decoder=__lowerCAmelCase , add_cross_attention=__lowerCAmelCase , decoder_start_token_id=__lowerCAmelCase , **__lowerCAmelCase , ) @property def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[Any] ): """simple docstring""" raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
83
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( _lowercase): snake_case__ : List[str] = "cvt" def __init__( self : Any , __lowerCAmelCase : Union[str, Any]=3 , __lowerCAmelCase : List[str]=[7, 3, 3] , __lowerCAmelCase : int=[4, 2, 2] , __lowerCAmelCase : int=[2, 1, 1] , __lowerCAmelCase : str=[6_4, 1_9_2, 3_8_4] , __lowerCAmelCase : Dict=[1, 3, 6] , __lowerCAmelCase : Optional[Any]=[1, 2, 1_0] , __lowerCAmelCase : Dict=[4.0, 4.0, 4.0] , __lowerCAmelCase : Dict=[0.0, 0.0, 0.0] , __lowerCAmelCase : Union[str, Any]=[0.0, 0.0, 0.0] , __lowerCAmelCase : int=[0.0, 0.0, 0.1] , __lowerCAmelCase : Union[str, Any]=[True, True, True] , __lowerCAmelCase : str=[False, False, True] , __lowerCAmelCase : List[str]=["dw_bn", "dw_bn", "dw_bn"] , __lowerCAmelCase : List[Any]=[3, 3, 3] , __lowerCAmelCase : Dict=[1, 1, 1] , __lowerCAmelCase : str=[2, 2, 2] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : Optional[Any]=[1, 1, 1] , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Any=1E-12 , **__lowerCAmelCase : int , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : int = patch_sizes _lowerCamelCase : Optional[Any] = patch_stride _lowerCamelCase : str = patch_padding _lowerCamelCase : Any = embed_dim _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : Dict = depth _lowerCamelCase : Optional[int] = mlp_ratio _lowerCamelCase : Any = attention_drop_rate _lowerCamelCase : Any = drop_rate _lowerCamelCase : Dict = drop_path_rate _lowerCamelCase : Optional[int] = qkv_bias _lowerCamelCase : int = cls_token _lowerCamelCase : int = qkv_projection_method _lowerCamelCase : Optional[Any] = kernel_qkv _lowerCamelCase : List[str] = padding_kv _lowerCamelCase : Tuple = stride_kv _lowerCamelCase : Union[str, Any] = padding_q _lowerCamelCase : Optional[Any] = stride_q _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps
83
1
"""simple docstring""" import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer 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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class __snake_case : def __init__( self : Dict , __lowerCAmelCase : str , __lowerCAmelCase : Tuple=1_3 , __lowerCAmelCase : Optional[int]=7 , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Optional[Any]=9_9 , __lowerCAmelCase : str=3_2 , __lowerCAmelCase : Dict=5 , __lowerCAmelCase : int=4 , __lowerCAmelCase : Tuple=4 , __lowerCAmelCase : List[str]="gelu" , __lowerCAmelCase : Dict=0.0 , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : str=True , __lowerCAmelCase : str=5_1_2 , __lowerCAmelCase : str=1_6 , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Optional[Any]=0.02 , __lowerCAmelCase : int=3 , __lowerCAmelCase : int=4 , __lowerCAmelCase : Union[str, Any]=None , ): """simple docstring""" _lowerCamelCase : int = parent _lowerCamelCase : Tuple = batch_size _lowerCamelCase : Any = seq_length _lowerCamelCase : List[Any] = is_training _lowerCamelCase : Union[str, Any] = use_input_mask _lowerCamelCase : Any = use_token_type_ids _lowerCamelCase : Tuple = use_labels _lowerCamelCase : Union[str, Any] = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Optional[Any] = num_hidden_layers _lowerCamelCase : Tuple = num_attention_heads _lowerCamelCase : Dict = intermediate_multiple_size _lowerCamelCase : str = hidden_act _lowerCamelCase : List[Any] = hidden_dropout _lowerCamelCase : Union[str, Any] = attention_dropout _lowerCamelCase : Tuple = weight_tying _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : str = type_sequence_label_size _lowerCamelCase : Union[str, Any] = initializer_range _lowerCamelCase : Dict = num_labels _lowerCamelCase : Union[str, Any] = num_choices _lowerCamelCase : int = scope def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : int = None if self.use_input_mask: _lowerCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : List[Any] = None if self.use_labels: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : Optional[Any] = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return GPTNeoXJapaneseConfig( 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_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() _lowerCamelCase : Optional[Any] = True return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : str = GPTNeoXJapaneseModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase ) _lowerCamelCase : int = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : str = True _lowerCamelCase : Optional[Any] = GPTNeoXJapaneseModel(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Union[str, Any] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[Any] = GPTNeoXJapaneseForCausalLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : List[str] = True _lowerCamelCase : Tuple = GPTNeoXJapaneseForCausalLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() # first forward pass _lowerCamelCase : Optional[Any] = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , use_cache=__lowerCAmelCase ) _lowerCamelCase : str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowerCamelCase : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _lowerCamelCase : Any = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _lowerCamelCase : List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _lowerCamelCase : List[Any] = torch.cat([input_mask, next_mask] , dim=-1 ) _lowerCamelCase : Any = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = output_from_no_past['''hidden_states'''][0] _lowerCamelCase : List[Any] = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , past_key_values=__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , )['''hidden_states'''][0] # select random slice _lowerCamelCase : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() _lowerCamelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() _lowerCamelCase : Union[str, Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : int = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Any = config_and_inputs _lowerCamelCase : Tuple = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , unittest.TestCase): snake_case__ : Union[str, Any] = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () snake_case__ : Optional[int] = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () snake_case__ : Union[str, Any] = ( {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) snake_case__ : str = False snake_case__ : Any = False snake_case__ : List[Any] = False snake_case__ : Dict = False def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = GPTNeoXJapaneseModelTester(self ) _lowerCamelCase : int = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() _lowerCamelCase : Dict = None self.model_tester.create_and_check_model_as_decoder(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*__lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : List[str] = '''abeja/gpt-neox-japanese-2.7b''' _lowerCamelCase : Any = ['''データサイエンティストとは、''', '''100年後に必要とされる会社は、''', '''フルリモートの環境で働くために必要なことは、''', '''国境の長いトンネルを抜けると''', '''美味しい日本食といえば、'''] _lowerCamelCase : Dict = [ '''データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。''', '''100年後に必要とされる会社は、「人」が中心の会社です。''', '''フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。''', '''国境の長いトンネルを抜けると、そこは雪国だった。''', '''美味しい日本食といえば、やっぱりお寿司ですよね。''', ] _lowerCamelCase : Optional[int] = GPTNeoXJapaneseTokenizer.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = GPTNeoXJapaneseForCausalLM.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : str = [] for prompt in prompts: _lowerCamelCase : Union[str, Any] = tokenizer(__lowerCAmelCase , return_tensors='''pt''' ).input_ids _lowerCamelCase : Optional[Any] = model.generate(__lowerCAmelCase , max_length=5_0 ) _lowerCamelCase : List[str] = tokenizer.batch_decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) predicted_outputs += generated_string self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
83
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __snake_case ( _lowercase): snake_case__ : torch.FloatTensor snake_case__ : torch.FloatTensor class __snake_case ( _lowercase , _lowercase): snake_case__ : int = 1 @register_to_config def __init__( self : str , __lowerCAmelCase : int = 2_0_0_0 , __lowerCAmelCase : float = 0.15 , __lowerCAmelCase : float = 0.01 , __lowerCAmelCase : float = 13_48.0 , __lowerCAmelCase : float = 1E-5 , __lowerCAmelCase : int = 1 , ): """simple docstring""" _lowerCamelCase : Optional[int] = sigma_max # setable values _lowerCamelCase : Dict = None self.set_sigmas(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[int] = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : Union[str, torch.device] = None ): """simple docstring""" _lowerCamelCase : Tuple = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCamelCase : Optional[int] = torch.linspace(1 , __lowerCAmelCase , __lowerCAmelCase , device=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None , __lowerCAmelCase : float = None ): """simple docstring""" _lowerCamelCase : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCamelCase : int = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCamelCase : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCamelCase : Optional[int] = torch.exp(torch.linspace(math.log(__lowerCAmelCase ) , math.log(__lowerCAmelCase ) , __lowerCAmelCase ) ) _lowerCamelCase : Tuple = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : int , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) _lowerCamelCase : Tuple = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCamelCase : Dict = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCamelCase : Optional[int] = timesteps.to(self.discrete_sigmas.device ) _lowerCamelCase : Any = self.discrete_sigmas[timesteps].to(sample.device ) _lowerCamelCase : int = self.get_adjacent_sigma(__lowerCAmelCase , __lowerCAmelCase ).to(sample.device ) _lowerCamelCase : Any = torch.zeros_like(__lowerCAmelCase ) _lowerCamelCase : Any = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCamelCase : Union[str, Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): _lowerCamelCase : List[Any] = diffusion.unsqueeze(-1 ) _lowerCamelCase : int = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCamelCase : List[str] = randn_tensor( sample.shape , layout=sample.layout , generator=__lowerCAmelCase , device=sample.device , dtype=sample.dtype ) _lowerCamelCase : List[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCamelCase : int = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=__lowerCAmelCase , prev_sample_mean=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : Optional[torch.Generator] = None , __lowerCAmelCase : bool = True , ): """simple docstring""" if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCamelCase : Union[str, Any] = randn_tensor(sample.shape , layout=sample.layout , generator=__lowerCAmelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr _lowerCamelCase : Union[str, Any] = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : Tuple = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() _lowerCamelCase : str = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCamelCase : Tuple = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCamelCase : Union[str, Any] = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): _lowerCamelCase : str = step_size.unsqueeze(-1 ) _lowerCamelCase : Any = sample + step_size * model_output _lowerCamelCase : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , __lowerCAmelCase : torch.FloatTensor , ): """simple docstring""" _lowerCamelCase : Dict = timesteps.to(original_samples.device ) _lowerCamelCase : Union[str, Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] _lowerCamelCase : Union[str, Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(__lowerCAmelCase ) * sigmas[:, None, None, None] ) _lowerCamelCase : int = noise + original_samples return noisy_samples def __len__( self : Optional[int] ): """simple docstring""" return self.config.num_train_timesteps
83
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : List[Any] = "table-transformer" snake_case__ : Dict = ["past_key_values"] snake_case__ : Tuple = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : List[Any] , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : List[Any]=3 , __lowerCAmelCase : Any=1_0_0 , __lowerCAmelCase : Optional[Any]=6 , __lowerCAmelCase : Optional[Any]=2_0_4_8 , __lowerCAmelCase : Any=8 , __lowerCAmelCase : List[str]=6 , __lowerCAmelCase : int=2_0_4_8 , __lowerCAmelCase : Optional[int]=8 , __lowerCAmelCase : Any=0.0 , __lowerCAmelCase : str=0.0 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : List[str]="relu" , __lowerCAmelCase : List[str]=2_5_6 , __lowerCAmelCase : int=0.1 , __lowerCAmelCase : Tuple=0.0 , __lowerCAmelCase : Optional[int]=0.0 , __lowerCAmelCase : Optional[int]=0.02 , __lowerCAmelCase : List[Any]=1.0 , __lowerCAmelCase : Tuple=False , __lowerCAmelCase : List[str]="sine" , __lowerCAmelCase : Any="resnet50" , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Any=1 , __lowerCAmelCase : Any=5 , __lowerCAmelCase : Optional[int]=2 , __lowerCAmelCase : List[Any]=1 , __lowerCAmelCase : Tuple=1 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : int=2 , __lowerCAmelCase : Dict=0.1 , **__lowerCAmelCase : Tuple , ): """simple docstring""" 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 : Tuple = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): _lowerCamelCase : Optional[int] = backbone_config.get('''model_type''' ) _lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] _lowerCamelCase : Tuple = config_class.from_dict(__lowerCAmelCase ) # set timm attributes to None _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = None, None, None _lowerCamelCase : Dict = use_timm_backbone _lowerCamelCase : List[str] = backbone_config _lowerCamelCase : Optional[int] = num_channels _lowerCamelCase : Optional[int] = num_queries _lowerCamelCase : Union[str, Any] = d_model _lowerCamelCase : str = encoder_ffn_dim _lowerCamelCase : Dict = encoder_layers _lowerCamelCase : List[Any] = encoder_attention_heads _lowerCamelCase : List[Any] = decoder_ffn_dim _lowerCamelCase : Any = decoder_layers _lowerCamelCase : List[str] = decoder_attention_heads _lowerCamelCase : Optional[Any] = dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = activation_dropout _lowerCamelCase : int = activation_function _lowerCamelCase : Dict = init_std _lowerCamelCase : List[Any] = init_xavier_std _lowerCamelCase : Any = encoder_layerdrop _lowerCamelCase : List[str] = decoder_layerdrop _lowerCamelCase : str = encoder_layers _lowerCamelCase : List[str] = auxiliary_loss _lowerCamelCase : Optional[Any] = position_embedding_type _lowerCamelCase : List[str] = backbone _lowerCamelCase : Union[str, Any] = use_pretrained_backbone _lowerCamelCase : Any = dilation # Hungarian matcher _lowerCamelCase : Optional[Any] = class_cost _lowerCamelCase : Tuple = bbox_cost _lowerCamelCase : Union[str, Any] = giou_cost # Loss coefficients _lowerCamelCase : List[str] = mask_loss_coefficient _lowerCamelCase : List[str] = dice_loss_coefficient _lowerCamelCase : List[str] = bbox_loss_coefficient _lowerCamelCase : Tuple = giou_loss_coefficient _lowerCamelCase : Optional[int] = eos_coefficient super().__init__(is_encoder_decoder=__lowerCAmelCase , **__lowerCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return self.d_model class __snake_case ( _lowercase): snake_case__ : Optional[int] = version.parse("1.11") @property def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return 1E-5 @property def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return 1_2
83
"""simple docstring""" from torch import nn def snake_case_ ( A_ : int ): '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F'''Unsupported activation function: {act_fn}''' )
83
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : Optional[int] = "blip_text_model" def __init__( self : str , __lowerCAmelCase : str=3_0_5_2_4 , __lowerCAmelCase : Any=7_6_8 , __lowerCAmelCase : int=7_6_8 , __lowerCAmelCase : Optional[Any]=3_0_7_2 , __lowerCAmelCase : Union[str, Any]=7_6_8 , __lowerCAmelCase : List[str]=1_2 , __lowerCAmelCase : int=8 , __lowerCAmelCase : List[str]=5_1_2 , __lowerCAmelCase : List[str]="gelu" , __lowerCAmelCase : Tuple=1E-12 , __lowerCAmelCase : Any=0.0 , __lowerCAmelCase : List[Any]=0.0 , __lowerCAmelCase : Any=0.02 , __lowerCAmelCase : Dict=3_0_5_2_2 , __lowerCAmelCase : int=2 , __lowerCAmelCase : List[Any]=0 , __lowerCAmelCase : Optional[int]=1_0_2 , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : List[str]=True , **__lowerCAmelCase : List[str] , ): """simple docstring""" super().__init__( pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , sep_token_id=__lowerCAmelCase , **__lowerCAmelCase , ) _lowerCamelCase : Union[str, Any] = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Tuple = encoder_hidden_size _lowerCamelCase : Union[str, Any] = intermediate_size _lowerCamelCase : Dict = projection_dim _lowerCamelCase : str = hidden_dropout_prob _lowerCamelCase : str = num_hidden_layers _lowerCamelCase : List[str] = num_attention_heads _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : Union[str, Any] = layer_norm_eps _lowerCamelCase : Any = hidden_act _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : List[str] = attention_probs_dropout_prob _lowerCamelCase : str = is_decoder _lowerCamelCase : int = use_cache @classmethod def SCREAMING_SNAKE_CASE ( cls : Tuple , __lowerCAmelCase : Union[str, os.PathLike] , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" cls._set_token_in_kwargs(__lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : Union[str, Any] = cls.get_config_dict(__lowerCAmelCase , **__lowerCAmelCase ) # get the text config dict if we are loading from BlipConfig if config_dict.get('''model_type''' ) == "blip": _lowerCamelCase : Optional[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__lowerCAmelCase , **__lowerCAmelCase ) class __snake_case ( _lowercase): snake_case__ : Any = "blip_vision_model" def __init__( self : int , __lowerCAmelCase : str=7_6_8 , __lowerCAmelCase : Union[str, Any]=3_0_7_2 , __lowerCAmelCase : List[Any]=5_1_2 , __lowerCAmelCase : Optional[int]=1_2 , __lowerCAmelCase : Dict=1_2 , __lowerCAmelCase : Optional[Any]=3_8_4 , __lowerCAmelCase : Any=1_6 , __lowerCAmelCase : Any="gelu" , __lowerCAmelCase : Optional[Any]=1E-5 , __lowerCAmelCase : Dict=0.0 , __lowerCAmelCase : Optional[Any]=1E-10 , **__lowerCAmelCase : Any , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = hidden_size _lowerCamelCase : List[Any] = intermediate_size _lowerCamelCase : Optional[int] = projection_dim _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Tuple = num_attention_heads _lowerCamelCase : List[str] = patch_size _lowerCamelCase : Optional[int] = image_size _lowerCamelCase : int = initializer_range _lowerCamelCase : Optional[int] = attention_dropout _lowerCamelCase : Optional[Any] = layer_norm_eps _lowerCamelCase : Optional[int] = hidden_act @classmethod def SCREAMING_SNAKE_CASE ( cls : Any , __lowerCAmelCase : Union[str, os.PathLike] , **__lowerCAmelCase : int ): """simple docstring""" cls._set_token_in_kwargs(__lowerCAmelCase ) _lowerCamelCase , _lowerCamelCase : Dict = cls.get_config_dict(__lowerCAmelCase , **__lowerCAmelCase ) # get the vision config dict if we are loading from BlipConfig if config_dict.get('''model_type''' ) == "blip": _lowerCamelCase : List[str] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__lowerCAmelCase , **__lowerCAmelCase ) class __snake_case ( _lowercase): snake_case__ : Any = "blip" snake_case__ : Any = True def __init__( self : Optional[int] , __lowerCAmelCase : str=None , __lowerCAmelCase : Dict=None , __lowerCAmelCase : Union[str, Any]=5_1_2 , __lowerCAmelCase : int=2.65_92 , __lowerCAmelCase : List[Any]=2_5_6 , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) if text_config is None: _lowerCamelCase : Optional[int] = {} logger.info('''`text_config` is `None`. Initializing the `BlipTextConfig` with default values.''' ) if vision_config is None: _lowerCamelCase : Dict = {} logger.info('''`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.''' ) _lowerCamelCase : Any = BlipTextConfig(**__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = BlipVisionConfig(**__lowerCAmelCase ) _lowerCamelCase : str = self.vision_config.hidden_size _lowerCamelCase : Dict = projection_dim _lowerCamelCase : Optional[Any] = logit_scale_init_value _lowerCamelCase : List[Any] = 1.0 _lowerCamelCase : int = 0.02 _lowerCamelCase : Dict = image_text_hidden_size @classmethod def SCREAMING_SNAKE_CASE ( cls : int , __lowerCAmelCase : BlipTextConfig , __lowerCAmelCase : BlipVisionConfig , **__lowerCAmelCase : str ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = copy.deepcopy(self.__dict__ ) _lowerCamelCase : str = self.text_config.to_dict() _lowerCamelCase : Union[str, Any] = self.vision_config.to_dict() _lowerCamelCase : Optional[int] = self.__class__.model_type return output
83
"""simple docstring""" def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def snake_case_ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(F'''| 0 | 0 | {nor_gate(0, 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0, 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1, 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1, 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
83
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 __snake_case ( _lowercase): def __init__( self : Tuple , __lowerCAmelCase : Optional[NestedDataStructureLike[PathLike]] = None , __lowerCAmelCase : Optional[NamedSplit] = None , __lowerCAmelCase : Optional[Features] = None , __lowerCAmelCase : str = None , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : Optional[int] = None , **__lowerCAmelCase : Any , ): """simple docstring""" _lowerCamelCase : Optional[int] = path_or_paths _lowerCamelCase : int = split if split or isinstance(__lowerCAmelCase , __lowerCAmelCase ) else '''train''' _lowerCamelCase : List[str] = features _lowerCamelCase : str = cache_dir _lowerCamelCase : List[str] = keep_in_memory _lowerCamelCase : List[str] = streaming _lowerCamelCase : int = num_proc _lowerCamelCase : List[str] = kwargs @abstractmethod def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" pass class __snake_case ( _lowercase): def __init__( self : int , __lowerCAmelCase : Optional[Features] = None , __lowerCAmelCase : str = None , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : Optional[int] = None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" _lowerCamelCase : List[str] = features _lowerCamelCase : List[str] = cache_dir _lowerCamelCase : str = keep_in_memory _lowerCamelCase : Optional[int] = streaming _lowerCamelCase : Optional[int] = num_proc _lowerCamelCase : List[str] = kwargs @abstractmethod def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" pass
83
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : list[list[int]] ): '''simple docstring''' for i in range(1, len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(A_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(A_ ) ): for j in range(1, len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
83
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = {'''configuration_focalnet''': ['''FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FocalNetConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FocalNetForImageClassification''', '''FocalNetForMaskedImageModeling''', '''FocalNetBackbone''', '''FocalNetModel''', '''FocalNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
83
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') class __snake_case ( Generic[T]): def __init__( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Optional[int] = data _lowerCamelCase : Node[T] | None = None def __str__( self : Optional[Any] ): """simple docstring""" return f'''{self.data}''' class __snake_case ( Generic[T]): def __init__( self : int ): """simple docstring""" _lowerCamelCase : Node[T] | None = None def __iter__( self : str ): """simple docstring""" _lowerCamelCase : List[str] = self.top while node: yield node.data _lowerCamelCase : Any = node.next def __str__( self : int ): """simple docstring""" return "->".join([str(__lowerCAmelCase ) for item in self] ) def __len__( self : int ): """simple docstring""" return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.top is None def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : T ): """simple docstring""" _lowerCamelCase : Tuple = Node(__lowerCAmelCase ) if not self.is_empty(): _lowerCamelCase : Optional[int] = self.top _lowerCamelCase : List[str] = node def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , __lowerCAmelCase ) _lowerCamelCase : Any = self.top _lowerCamelCase : Any = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : List[str] = None if __name__ == "__main__": from doctest import testmod testmod()
83
1
"""simple docstring""" from math import factorial def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' if n < k or k < 0: raise ValueError('''Please enter positive integers for n and k where n >= k''' ) return factorial(A_ ) // (factorial(A_ ) * factorial(n - k )) if __name__ == "__main__": print( '''The number of five-card hands possible from a standard''', F"""fifty-two card deck is: {combinations(52, 5)}\n""", ) print( '''If a class of 40 students must be arranged into groups of''', F"""4 for group projects, there are {combinations(40, 4)} ways""", '''to arrange them.\n''', ) print( '''If 10 teams are competing in a Formula One race, there''', F"""are {combinations(10, 3)} ways that first, second and""", '''third place can be awarded.''', )
83
"""simple docstring""" import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase__ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCAmelCase__ = spec.loader.load_module() lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCAmelCase__ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = [] for config_class in list(CONFIG_MAPPING.values() ): _lowerCamelCase : Tuple = False # source code of `config_class` _lowerCamelCase : int = inspect.getsource(A_ ) _lowerCamelCase : str = _re_checkpoint.findall(A_ ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` _lowerCamelCase , _lowerCamelCase : Tuple = checkpoint # verify the checkpoint name corresponds to the checkpoint link _lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: _lowerCamelCase : Union[str, Any] = True break _lowerCamelCase : Tuple = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(A_ ) if len(A_ ) > 0: _lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
83
1
"""simple docstring""" 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 __snake_case ( _lowercase , unittest.TestCase): snake_case__ : Optional[Any] = MarianTokenizer snake_case__ : int = False snake_case__ : Tuple = True def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" super().setUp() _lowerCamelCase : Dict = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] _lowerCamelCase : Any = dict(zip(__lowerCAmelCase , range(len(__lowerCAmelCase ) ) ) ) _lowerCamelCase : int = 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 : List[Any] = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , **__lowerCAmelCase : List[str] ): """simple docstring""" return MarianTokenizer.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : str ): """simple docstring""" return ( "This is a test", "This is a test", ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : List[str] = '''</s>''' _lowerCamelCase : Optional[int] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCAmelCase ) , __lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCAmelCase ) , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _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 SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Optional[int] = MarianTokenizer.from_pretrained(f'''{ORG_NAME}opus-mt-en-de''' ) _lowerCamelCase : Dict = en_de_tokenizer(['''I am a small frog'''] , return_tensors=__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[Any] = [3_8, 1_2_1, 1_4, 6_9_7, 3_8_8_4_8, 0] self.assertListEqual(__lowerCAmelCase , batch.input_ids[0] ) _lowerCamelCase : Any = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : List[str] = [x.name for x in Path(__lowerCAmelCase ).glob('''*''' )] self.assertIn('''source.spm''' , __lowerCAmelCase ) MarianTokenizer.from_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = self.get_tokenizer() _lowerCamelCase : Tuple = tok( ['''I am a small frog''' * 1_0_0_0, '''I am a small frog'''] , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(batch.input_ids.shape , (2, 5_1_2) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.get_tokenizer() _lowerCamelCase : List[Any] = 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, 1_0) ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : int = {'''input_ids''': [[4_3_4_9_5, 4_6_2, 2_0, 4_2_1_6_4, 1_3_6_9, 5_2, 4_6_4, 1_3_2, 1_7_0_3, 4_9_2, 1_3, 7_4_9_1, 3_8_9_9_9, 6, 8, 4_6_4, 1_3_2, 1_7_0_3, 4_9_2, 1_3, 4_6_6_9, 3_7_8_6_7, 1_3, 7_5_2_5, 2_7, 1_5_9_3, 9_8_8, 1_3, 3_3_9_7_2, 7_0_2_9, 6, 2_0, 8_2_5_1, 3_8_3, 2, 2_7_0, 5_8_6_6, 3_7_8_8, 2, 2_3_5_3, 8_2_5_1, 1_2_3_3_8, 2, 1_3_9_5_8, 3_8_7, 2, 3_6_2_9, 6_9_5_3, 1_8_8, 2_9_0_0, 2, 1_3_9_5_8, 8_0_1_1, 1_1_5_0_1, 2_3, 8_4_6_0, 4_0_7_3, 3_4_0_0_9, 2_0, 4_3_5, 1_1_4_3_9, 2_7, 8, 8_4_6_0, 4_0_7_3, 6_0_0_4, 2_0, 9_9_8_8, 3_7_5, 2_7, 3_3, 2_6_6, 1_9_4_5, 1_0_7_6, 1_3_5_0, 3_7_8_6_7, 3_2_8_8, 5, 5_7_7, 1_0_7_6, 4_3_7_4, 8, 5_0_8_2, 5, 2_6_4_5_3, 2_5_7, 5_5_6, 4_0_3, 2, 2_4_2, 1_3_2, 3_8_3, 3_1_6, 4_9_2, 8, 1_0_7_6_7, 6, 3_1_6, 3_0_4, 4_2_3_9, 3, 0], [1_4_8, 1_5_7_2_2, 1_9, 1_8_3_9, 1_2, 1_3_5_0, 1_3, 2_2_3_2_7, 5_0_8_2, 5_4_1_8, 4_7_5_6_7, 3_5_9_3_8, 5_9, 3_1_8, 1_9_5_5_2, 1_0_8, 2_1_8_3, 5_4, 1_4_9_7_6, 4_8_3_5, 3_2, 5_4_7, 1_1_1_4, 8, 3_1_5, 2_4_1_7, 5, 9_2, 1_9_0_8_8, 3, 0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0], [3_6, 6_3_9_5, 1_2_5_7_0, 3_9_1_4_7, 1_1_5_9_7, 6, 2_6_6, 4, 4_5_4_0_5, 7_2_9_6, 3, 0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[str] = MarianTokenizer.from_pretrained('''hf-internal-testing/test-marian-two-vocabs''' ) _lowerCamelCase : int = '''Tämä on testi''' _lowerCamelCase : List[str] = '''This is a test''' _lowerCamelCase : Any = [7_6, 7, 2_0_4_7, 2] _lowerCamelCase : Optional[int] = [6_9, 1_2, 1_1, 9_4_0, 2] _lowerCamelCase : int = tokenizer(__lowerCAmelCase ).input_ids self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Dict = tokenizer(text_target=__lowerCAmelCase ).input_ids self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Any = tokenizer.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase )
83
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class __snake_case ( unittest.TestCase): pass @nightly @require_torch_gpu class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : int = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : str = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Dict = torch.manual_seed(0 ) _lowerCamelCase : List[Any] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCAmelCase ) _lowerCamelCase : Tuple = VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : int = generator.manual_seed(0 ) _lowerCamelCase : List[str] = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = '''A painting of a squirrel eating a burger ''' _lowerCamelCase : Optional[int] = torch.manual_seed(0 ) _lowerCamelCase : int = pipe( prompt=__lowerCAmelCase , generator=__lowerCAmelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images _lowerCamelCase : List[str] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) _lowerCamelCase : Dict = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
83
1