code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCamelCase_ ( _lowercase , unittest.TestCase ): lowerCAmelCase__ = FlaxAutoencoderKL @property def lowercase_ ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : Dict = 4 UpperCAmelCase__ : List[str] = 3 UpperCAmelCase__ : List[Any] = (32, 32) UpperCAmelCase__ : str = jax.random.PRNGKey(0 ) UpperCAmelCase__ : int = jax.random.uniform(__lowerCAmelCase , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } UpperCAmelCase__ : Tuple = self.dummy_input return init_dict, inputs_dict
181
"""simple docstring""" import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def snake_case_ ( A_ : Tuple, A_ : int, A_ : Dict ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = LxmertConfig.from_json_file(A_ ) print(F'''Building PyTorch model from configuration: {config}''' ) _lowerCamelCase : List[str] = LxmertForPreTraining(A_ ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(A_, A_, A_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict(), A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
72
0
'''simple docstring''' def UpperCAmelCase_ ( __lowerCamelCase : list[list[float]] ): lowercase_ :list[list[float]] = [] for data in source_data: for i, el in enumerate(A_ ): if len(A_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(A_ ) ) return data_lists def UpperCAmelCase_ ( __lowerCamelCase : list[list[float]] ,__lowerCamelCase : list[int] ): lowercase_ :list[list[float]] = [] for dlist, weight in zip(A_ ,A_ ): lowercase_ :Any = min(A_ ) lowercase_ :Optional[Any] = max(A_ ) lowercase_ :list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: lowercase_ :str = F'Invalid weight of {weight:f} provided' raise ValueError(A_ ) score_lists.append(A_ ) return score_lists def UpperCAmelCase_ ( __lowerCamelCase : list[list[float]] ): lowercase_ :list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(A_ ): lowercase_ :List[str] = final_scores[j] + ele return final_scores def UpperCAmelCase_ ( __lowerCamelCase : list[list[float]] ,__lowerCamelCase : list[int] ): lowercase_ :Tuple = get_data(A_ ) lowercase_ :Optional[Any] = calculate_each_score(A_ ,A_ ) lowercase_ :str = generate_final_scores(A_ ) # append scores to source data for i, ele in enumerate(A_ ): source_data[i].append(A_ ) return source_data
223
"""simple docstring""" from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def snake_case_ ( ): '''simple docstring''' _lowerCamelCase , _lowerCamelCase : int = 9, 14 # noqa: F841 _lowerCamelCase : List[Any] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] _lowerCamelCase : Any = defaultdict(A_ ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) _lowerCamelCase : List[str] = mst(A_ ) _lowerCamelCase : Optional[int] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: _lowerCamelCase : int = tuple(answer[:2] ) _lowerCamelCase : int = tuple(edge[::-1] ) assert edge in result or reverse in result
72
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ : str = { '''configuration_rembert''': ['''REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RemBertConfig''', '''RemBertOnnxConfig'''] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : int = ['''RemBertTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : Tuple = ['''RemBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : List[Any] = [ '''REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RemBertForCausalLM''', '''RemBertForMaskedLM''', '''RemBertForMultipleChoice''', '''RemBertForQuestionAnswering''', '''RemBertForSequenceClassification''', '''RemBertForTokenClassification''', '''RemBertLayer''', '''RemBertModel''', '''RemBertPreTrainedModel''', '''load_tf_weights_in_rembert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : List[str] = [ '''TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRemBertForCausalLM''', '''TFRemBertForMaskedLM''', '''TFRemBertForMultipleChoice''', '''TFRemBertForQuestionAnswering''', '''TFRemBertForSequenceClassification''', '''TFRemBertForTokenClassification''', '''TFRemBertLayer''', '''TFRemBertModel''', '''TFRemBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys lowerCamelCase__ : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
246
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart lowerCAmelCase__ = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } lowerCAmelCase__ = { '''facebook/bart-base''': 1024, '''facebook/bart-large''': 1024, '''facebook/bart-large-mnli''': 1024, '''facebook/bart-large-cnn''': 1024, '''facebook/bart-large-xsum''': 1024, '''yjernite/bart_eli5''': 1024, } class __snake_case ( _lowercase): snake_case__ : Any = VOCAB_FILES_NAMES snake_case__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Optional[int] = ["input_ids", "attention_mask"] snake_case__ : Any = BartTokenizer def __init__( self : int , __lowerCAmelCase : Dict=None , __lowerCAmelCase : int=None , __lowerCAmelCase : Dict=None , __lowerCAmelCase : List[Any]="replace" , __lowerCAmelCase : Any="<s>" , __lowerCAmelCase : Optional[int]="</s>" , __lowerCAmelCase : str="</s>" , __lowerCAmelCase : Dict="<s>" , __lowerCAmelCase : Union[str, Any]="<unk>" , __lowerCAmelCase : Any="<pad>" , __lowerCAmelCase : Optional[Any]="<mask>" , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=True , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" super().__init__( __lowerCAmelCase , __lowerCAmelCase , tokenizer_file=__lowerCAmelCase , errors=__lowerCAmelCase , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase , trim_offsets=__lowerCAmelCase , **__lowerCAmelCase , ) _lowerCamelCase : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __lowerCAmelCase ) != add_prefix_space: _lowerCamelCase : Dict = getattr(__lowerCAmelCase , pre_tok_state.pop('''type''' ) ) _lowerCamelCase : Any = add_prefix_space _lowerCamelCase : int = pre_tok_class(**__lowerCAmelCase ) _lowerCamelCase : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _lowerCamelCase : List[str] = '''post_processor''' _lowerCamelCase : List[str] = getattr(self.backend_tokenizer , __lowerCAmelCase , __lowerCAmelCase ) if tokenizer_component_instance: _lowerCamelCase : int = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _lowerCamelCase : Tuple = tuple(state['''sep'''] ) if "cls" in state: _lowerCamelCase : int = tuple(state['''cls'''] ) _lowerCamelCase : Union[str, Any] = False if state.get('''add_prefix_space''' , __lowerCAmelCase ) != add_prefix_space: _lowerCamelCase : Dict = add_prefix_space _lowerCamelCase : Optional[Any] = True if state.get('''trim_offsets''' , __lowerCAmelCase ) != trim_offsets: _lowerCamelCase : Any = trim_offsets _lowerCamelCase : str = True if changes_to_apply: _lowerCamelCase : List[str] = getattr(__lowerCAmelCase , state.pop('''type''' ) ) _lowerCamelCase : str = component_class(**__lowerCAmelCase ) setattr(self.backend_tokenizer , __lowerCAmelCase , __lowerCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : Tuple = AddedToken(__lowerCAmelCase , lstrip=__lowerCAmelCase , rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else value _lowerCamelCase : str = value def SCREAMING_SNAKE_CASE ( self : int , *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Dict = kwargs.get('''is_split_into_words''' , __lowerCAmelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , *__lowerCAmelCase : Tuple , **__lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Any = kwargs.get('''is_split_into_words''' , __lowerCAmelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[str] = None ): """simple docstring""" _lowerCamelCase : Tuple = self._tokenizer.model.save(__lowerCAmelCase , name=__lowerCAmelCase ) return tuple(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=None ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ): """simple docstring""" _lowerCamelCase : List[str] = [self.sep_token_id] _lowerCamelCase : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
72
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int=13 , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : List[Any]=32 , UpperCAmelCase_ : Optional[int]=5 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : Tuple=37 , UpperCAmelCase_ : Union[str, Any]="gelu" , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : List[str]=16 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : List[str]=None , ) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =parent lowerCamelCase__: Union[str, Any] =batch_size lowerCamelCase__: Optional[Any] =seq_length lowerCamelCase__: Optional[Any] =is_training lowerCamelCase__: Optional[int] =use_token_type_ids lowerCamelCase__: str =use_labels lowerCamelCase__: Optional[Any] =vocab_size lowerCamelCase__: int =hidden_size lowerCamelCase__: int =num_hidden_layers lowerCamelCase__: List[Any] =num_attention_heads lowerCamelCase__: str =intermediate_size lowerCamelCase__: Tuple =hidden_act lowerCamelCase__: Optional[int] =hidden_dropout_prob lowerCamelCase__: int =attention_probs_dropout_prob lowerCamelCase__: Dict =max_position_embeddings lowerCamelCase__: Optional[int] =type_vocab_size lowerCamelCase__: int =type_sequence_label_size lowerCamelCase__: Tuple =initializer_range lowerCamelCase__: Union[str, Any] =num_labels lowerCamelCase__: Any =num_choices lowerCamelCase__: str =scope lowerCamelCase__: List[Any] =self.vocab_size - 1 def SCREAMING_SNAKE_CASE_ (self : int) ->int: '''simple docstring''' lowerCamelCase__: Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) lowerCamelCase__: str =None if self.use_token_type_ids: lowerCamelCase__: Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) lowerCamelCase__: int =None lowerCamelCase__: List[str] =None lowerCamelCase__: Optional[int] =None if self.use_labels: lowerCamelCase__: Optional[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size) lowerCamelCase__: int =ids_tensor([self.batch_size, self.seq_length] , self.num_labels) lowerCamelCase__: Union[str, Any] =ids_tensor([self.batch_size] , self.num_choices) lowerCamelCase__: Any =OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) lowerCamelCase__: Union[str, Any] =ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , *UpperCAmelCase_ : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =OpenAIGPTModel(config=__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCamelCase__: Dict =model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase , head_mask=__lowerCAmelCase) lowerCamelCase__: Dict =model(__lowerCAmelCase , token_type_ids=__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 : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , *UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' lowerCamelCase__: Union[str, Any] =OpenAIGPTLMHeadModel(__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCamelCase__: Optional[Any] =model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] , *UpperCAmelCase_ : int) ->List[str]: '''simple docstring''' lowerCamelCase__: Any =OpenAIGPTDoubleHeadsModel(__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCamelCase__: int =model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , *UpperCAmelCase_ : List[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.num_labels lowerCamelCase__: int =OpenAIGPTForSequenceClassification(__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCamelCase__: Union[str, Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size) lowerCamelCase__: Tuple =model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : Any) ->List[Any]: '''simple docstring''' lowerCamelCase__: str =self.prepare_config_and_inputs() ( lowerCamelCase__ ): List[Any] =config_and_inputs lowerCamelCase__: str ={ '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' lowercase_ = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowercase_ = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowercase_ = ( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=False) ->List[str]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =super()._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": lowerCamelCase__: Dict =torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=__lowerCAmelCase , ) lowerCamelCase__: Any =inputs_dict['''labels'''] lowerCamelCase__: Optional[int] =inputs_dict['''labels'''] lowerCamelCase__: Any =torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=__lowerCAmelCase , ) lowerCamelCase__: str =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase) return inputs_dict def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: int =OpenAIGPTModelTester(self) lowerCamelCase__: List[str] =ConfigTester(self , config_class=__lowerCAmelCase , n_embd=37) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ (self : int) ->List[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*__lowerCAmelCase) def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*__lowerCAmelCase) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->str: '''simple docstring''' lowerCamelCase__: List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*__lowerCAmelCase) def SCREAMING_SNAKE_CASE_ (self : str) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__lowerCAmelCase) @slow def SCREAMING_SNAKE_CASE_ (self : Any) ->Any: '''simple docstring''' for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__: Tuple =OpenAIGPTModel.from_pretrained(__lowerCAmelCase) self.assertIsNotNone(__lowerCAmelCase) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->int: '''simple docstring''' lowerCamelCase__: List[str] =OpenAIGPTLMHeadModel.from_pretrained("openai-gpt") model.to(__lowerCAmelCase) lowerCamelCase__: Tuple =torch.tensor([[481, 4_735, 544]] , dtype=torch.long , device=__lowerCAmelCase) # the president is lowerCamelCase__: List[str] =[ 481, 4_735, 544, 246, 963, 870, 762, 239, 244, 40_477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the lowerCamelCase__: int =model.generate(__lowerCAmelCase , do_sample=__lowerCAmelCase) self.assertListEqual(output_ids[0].tolist() , __lowerCAmelCase)
10
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : str ): '''simple docstring''' return [ord(A_ ) - 96 for elem in plain] def snake_case_ ( A_ : list[int] ): '''simple docstring''' return "".join(chr(elem + 96 ) for elem in encoded ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Dict = encode(input('''-> ''' ).strip().lower() ) print('''Encoded: ''', A_ ) print('''Decoded:''', decode(A_ ) ) if __name__ == "__main__": main()
72
0
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __lowerCAmelCase ( _lowercase ): """simple docstring""" snake_case_ = ["vqvae"] def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> Any: '''simple docstring''' super().__init__() self.register_modules(unet=__lowerCAmelCase , scheduler=__lowerCAmelCase , mel=__lowerCAmelCase , vqvae=__lowerCAmelCase ) def lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' return 50 if isinstance(self.scheduler , __lowerCAmelCase ) else 1_000 @torch.no_grad() def __call__( self , lowerCamelCase__ = 1 , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = 0 , lowerCamelCase__ = 0 , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = 0 , lowerCamelCase__ = 0 , lowerCamelCase__ = None , lowerCamelCase__ = 0 , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__=True , ) -> List[Any]: '''simple docstring''' __lowerCamelCase = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCAmelCase ) __lowerCamelCase = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: __lowerCamelCase = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: __lowerCamelCase = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCAmelCase , device=self.device , ) __lowerCamelCase = noise __lowerCamelCase = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = self.mel.audio_slice_to_image(__lowerCAmelCase ) __lowerCamelCase = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) __lowerCamelCase = (input_image / 255) * 2 - 1 __lowerCamelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: __lowerCamelCase = self.vqvae.encode(torch.unsqueeze(__lowerCAmelCase , 0 ) ).latent_dist.sample( generator=__lowerCAmelCase )[0] __lowerCamelCase = self.vqvae.config.scaling_factor * input_images if start_step > 0: __lowerCamelCase = self.scheduler.add_noise(__lowerCAmelCase , __lowerCAmelCase , self.scheduler.timesteps[start_step - 1] ) __lowerCamelCase = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) __lowerCamelCase = int(mask_start_secs * pixels_per_second ) __lowerCamelCase = int(mask_end_secs * pixels_per_second ) __lowerCamelCase = self.scheduler.add_noise(__lowerCAmelCase , __lowerCAmelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCAmelCase ): __lowerCamelCase = self.unet(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )['''sample'''] else: __lowerCamelCase = self.unet(__lowerCAmelCase , __lowerCAmelCase )['''sample'''] if isinstance(self.scheduler , __lowerCAmelCase ): __lowerCamelCase = self.scheduler.step( model_output=__lowerCAmelCase , timestep=__lowerCAmelCase , sample=__lowerCAmelCase , eta=__lowerCAmelCase , generator=__lowerCAmelCase , )['''prev_sample'''] else: __lowerCamelCase = self.scheduler.step( model_output=__lowerCAmelCase , timestep=__lowerCAmelCase , sample=__lowerCAmelCase , generator=__lowerCAmelCase , )['''prev_sample'''] if mask is not None: if mask_start > 0: __lowerCamelCase = mask[:, step, :, :mask_start] if mask_end > 0: __lowerCamelCase = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance __lowerCamelCase = 1 / self.vqvae.config.scaling_factor * images __lowerCamelCase = self.vqvae.decode(__lowerCAmelCase )['''sample'''] __lowerCamelCase = (images / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() __lowerCamelCase = (images * 255).round().astype('uint8' ) __lowerCamelCase = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCAmelCase , mode='RGB' ).convert('L' ) for _ in images) ) __lowerCamelCase = [self.mel.image_to_audio(__lowerCAmelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCAmelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCAmelCase ) ) @torch.no_grad() def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = 50 ) -> Optional[int]: '''simple docstring''' assert isinstance(self.scheduler , __lowerCAmelCase ) self.scheduler.set_timesteps(__lowerCAmelCase ) __lowerCamelCase = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) __lowerCamelCase = (sample / 255) * 2 - 1 __lowerCamelCase = torch.Tensor(__lowerCAmelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): __lowerCamelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps __lowerCamelCase = self.scheduler.alphas_cumprod[t] __lowerCamelCase = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) __lowerCamelCase = 1 - alpha_prod_t __lowerCamelCase = self.unet(__lowerCAmelCase , __lowerCAmelCase )['''sample'''] __lowerCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output __lowerCamelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) __lowerCamelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def lowercase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: '''simple docstring''' __lowerCamelCase = acos(torch.dot(torch.flatten(__lowerCAmelCase ) , torch.flatten(__lowerCAmelCase ) ) / torch.norm(__lowerCAmelCase ) / torch.norm(__lowerCAmelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCAmelCase ) + sin(alpha * theta ) * xa / sin(__lowerCAmelCase )
90
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_lxmert''': ['''LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LxmertConfig'''], '''tokenization_lxmert''': ['''LxmertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''LxmertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''LxmertEncoder''', '''LxmertForPreTraining''', '''LxmertForQuestionAnswering''', '''LxmertModel''', '''LxmertPreTrainedModel''', '''LxmertVisualFeatureEncoder''', '''LxmertXLayer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLxmertForPreTraining''', '''TFLxmertMainLayer''', '''TFLxmertModel''', '''TFLxmertPreTrainedModel''', '''TFLxmertVisualFeatureEncoder''', ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__: List[str] = {'configuration_mmbt': ['MMBTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__: List[str] = ['MMBTForClassification', 'MMBTModel', 'ModalEmbeddings'] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a__: List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
193
"""simple docstring""" def snake_case_ ( A_ : list[list[float]] ): '''simple docstring''' _lowerCamelCase : list[list[float]] = [] for data in source_data: for i, el in enumerate(A_ ): if len(A_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(A_ ) ) return data_lists def snake_case_ ( A_ : list[list[float]], A_ : list[int] ): '''simple docstring''' _lowerCamelCase : list[list[float]] = [] for dlist, weight in zip(A_, A_ ): _lowerCamelCase : Any = min(A_ ) _lowerCamelCase : Optional[Any] = max(A_ ) _lowerCamelCase : list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: _lowerCamelCase : str = F'''Invalid weight of {weight:f} provided''' raise ValueError(A_ ) score_lists.append(A_ ) return score_lists def snake_case_ ( A_ : list[list[float]] ): '''simple docstring''' _lowerCamelCase : list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(A_ ): _lowerCamelCase : List[str] = final_scores[j] + ele return final_scores def snake_case_ ( A_ : list[list[float]], A_ : list[int] ): '''simple docstring''' _lowerCamelCase : Tuple = get_data(A_ ) _lowerCamelCase : Optional[Any] = calculate_each_score(A_, A_ ) _lowerCamelCase : str = generate_final_scores(A_ ) # append scores to source data for i, ele in enumerate(A_ ): source_data[i].append(A_ ) return source_data
72
0
from torch import nn class A_ ( nn.Module ): def __init__( self : Any , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Union[str, Any] ) -> List[str]: super().__init__() __lowerCAmelCase: Optional[Any] = class_size __lowerCAmelCase: Optional[Any] = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) __lowerCAmelCase: List[str] = nn.Linear(__lowerCAmelCase , __lowerCAmelCase ) def UpperCAmelCase ( self : Optional[int] , UpperCAmelCase : int ) -> Union[str, Any]: __lowerCAmelCase: List[Any] = self.mlp(__lowerCAmelCase ) return logits
322
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''microsoft/unispeech-large-1500h-cv''': ( '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json''' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class __snake_case ( _lowercase): snake_case__ : List[str] = "unispeech" def __init__( self : List[str] , __lowerCAmelCase : List[Any]=3_2 , __lowerCAmelCase : str=7_6_8 , __lowerCAmelCase : int=1_2 , __lowerCAmelCase : int=1_2 , __lowerCAmelCase : int=3_0_7_2 , __lowerCAmelCase : Tuple="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : Tuple=0.0 , __lowerCAmelCase : Optional[int]=0.0 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : Dict=1E-5 , __lowerCAmelCase : Optional[int]="group" , __lowerCAmelCase : Dict="gelu" , __lowerCAmelCase : int=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , __lowerCAmelCase : Optional[int]=(5, 2, 2, 2, 2, 2, 2) , __lowerCAmelCase : Union[str, Any]=(1_0, 3, 3, 3, 3, 2, 2) , __lowerCAmelCase : List[Any]=False , __lowerCAmelCase : List[str]=1_2_8 , __lowerCAmelCase : Any=1_6 , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Union[str, Any]=0.05 , __lowerCAmelCase : Union[str, Any]=1_0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : Dict=0.0 , __lowerCAmelCase : Optional[int]=1_0 , __lowerCAmelCase : Dict=0 , __lowerCAmelCase : List[str]=3_2_0 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : Tuple=1_0_0 , __lowerCAmelCase : Dict=2_5_6 , __lowerCAmelCase : str=2_5_6 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : Dict="mean" , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : Optional[Any]=2_5_6 , __lowerCAmelCase : Dict=8_0 , __lowerCAmelCase : int=0 , __lowerCAmelCase : Optional[int]=1 , __lowerCAmelCase : Dict=2 , __lowerCAmelCase : Any=0.5 , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" super().__init__(**__lowerCAmelCase , pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase ) _lowerCamelCase : Dict = hidden_size _lowerCamelCase : Any = feat_extract_norm _lowerCamelCase : List[Any] = feat_extract_activation _lowerCamelCase : Any = list(__lowerCAmelCase ) _lowerCamelCase : Tuple = list(__lowerCAmelCase ) _lowerCamelCase : int = list(__lowerCAmelCase ) _lowerCamelCase : List[str] = conv_bias _lowerCamelCase : List[str] = num_conv_pos_embeddings _lowerCamelCase : Tuple = num_conv_pos_embedding_groups _lowerCamelCase : List[str] = len(self.conv_dim ) _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : List[Any] = intermediate_size _lowerCamelCase : Dict = hidden_act _lowerCamelCase : Union[str, Any] = num_attention_heads _lowerCamelCase : Tuple = hidden_dropout _lowerCamelCase : List[Any] = attention_dropout _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Optional[Any] = feat_proj_dropout _lowerCamelCase : Optional[int] = final_dropout _lowerCamelCase : Any = layerdrop _lowerCamelCase : Any = layer_norm_eps _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : List[str] = num_ctc_classes _lowerCamelCase : List[Any] = vocab_size _lowerCamelCase : Optional[Any] = do_stable_layer_norm _lowerCamelCase : Tuple = use_weighted_layer_sum _lowerCamelCase : List[Any] = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _lowerCamelCase : Any = apply_spec_augment _lowerCamelCase : Dict = mask_time_prob _lowerCamelCase : List[str] = mask_time_length _lowerCamelCase : Optional[Any] = mask_time_min_masks _lowerCamelCase : List[str] = mask_feature_prob _lowerCamelCase : int = mask_feature_length _lowerCamelCase : Dict = mask_feature_min_masks # parameters for pretraining with codevector quantized representations _lowerCamelCase : Optional[Any] = num_codevectors_per_group _lowerCamelCase : int = num_codevector_groups _lowerCamelCase : List[Any] = contrastive_logits_temperature _lowerCamelCase : List[str] = feat_quantizer_dropout _lowerCamelCase : Dict = num_negatives _lowerCamelCase : Optional[int] = codevector_dim _lowerCamelCase : List[Any] = proj_codevector_dim _lowerCamelCase : List[Any] = diversity_loss_weight # ctc loss _lowerCamelCase : Union[str, Any] = ctc_loss_reduction _lowerCamelCase : Any = ctc_zero_infinity # pretraining loss _lowerCamelCase : str = replace_prob @property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
72
0
"""simple docstring""" __UpperCamelCase : str = [0, 2, 4, 6, 8] __UpperCamelCase : str = [1, 3, 5, 7, 9] def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ ): if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 lowerCAmelCase__ : int = 0 for digit in range(10 ): lowerCAmelCase__ : List[str] = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , A_ , A_ ) return result lowerCAmelCase__ : List[Any] = 0 for digita in range(10 ): lowerCAmelCase__ : List[str] = digita if (remainder + digita) % 2 == 0: lowerCAmelCase__ : Tuple = ODD_DIGITS else: lowerCAmelCase__ : List[str] = EVEN_DIGITS for digita in other_parity_digits: lowerCAmelCase__ : int = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , A_ , A_ , ) return result def __SCREAMING_SNAKE_CASE ( A_ = 9 ): lowerCAmelCase__ : Optional[Any] = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(A_ , 0 , [0] * length , A_ ) return result if __name__ == "__main__": print(F'''{solution() = }''')
106
"""simple docstring""" from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def snake_case_ ( A_ : str, A_ : str, A_ : Optional[str] = None ): '''simple docstring''' if version.parse(hfh.__version__ ).release < version.parse('''0.11.0''' ).release: # old versions of hfh don't url-encode the file path _lowerCamelCase : Optional[Any] = quote(A_ ) return hfh.hf_hub_url(A_, A_, repo_type='''dataset''', revision=A_ )
72
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Optional[int] = current_set.copy() for row_index, row in enumerate(A_ ): lowerCAmelCase__ : Tuple = row[0] for column_index, column in enumerate(A_ ): if magnitude == 0: lowerCAmelCase__ : List[Any] = column continue lowerCAmelCase__ : List[Any] = column / magnitude # Subtract to cancel term lowerCAmelCase__ : Union[str, Any] = current_set[0] lowerCAmelCase__ : Dict = [first_row] lowerCAmelCase__ : str = current_set[1::] for row in current_set: lowerCAmelCase__ : Union[str, Any] = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(A_ ) continue for column_index in range(len(A_ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(A_ ) # Create next recursion iteration set if len(final_set[0] ) != 3: lowerCAmelCase__ : Any = final_set[0] lowerCAmelCase__ : Any = [] lowerCAmelCase__ : Optional[int] = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) lowerCAmelCase__ : Dict = simplify(A_ ) for i in range(len(A_ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , A_ ) lowerCAmelCase__ : Tuple = resultant return final_set def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" if len(A_ ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) lowerCAmelCase__ : Dict = len(A_ ) + 1 if any(len(A_ ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(A_ , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(A_ ) == 1: return [equations[0][-1] / equations[0][0]] lowerCAmelCase__ : Optional[Any] = equations.copy() if any(0 in row for row in data_set ): lowerCAmelCase__ : str = data_set.copy() lowerCAmelCase__ : List[Any] = [] for row_index, row in enumerate(A_ ): if 0 not in row: lowerCAmelCase__ : Union[str, Any] = data_set.pop(A_ ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , A_ ) lowerCAmelCase__ : List[str] = data_set.copy() lowerCAmelCase__ : int = simplify(A_ ) lowerCAmelCase__ : int = simplified[::-1] lowerCAmelCase__ : list = [] for row in simplified: lowerCAmelCase__ : Tuple = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue lowerCAmelCase__ : Optional[Any] = row.copy()[: len(A_ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(A_ ) == 0: solutions.append(0 ) continue lowerCAmelCase__ : Tuple = temp_row[1::] lowerCAmelCase__ : Tuple = temp_row[::-1] for column_index, column in enumerate(A_ ): current_solution -= column * solutions[column_index] solutions.append(A_ ) lowerCAmelCase__ : Optional[int] = [] for item in solutions: final.append(float(round(A_ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() _lowerCAmelCase = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
37
"""simple docstring""" import unittest import numpy as np def snake_case_ ( A_ : np.ndarray, A_ : np.ndarray, A_ : np.ndarray, A_ : np.ndarray | None = None, ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = np.shape(A_ ) _lowerCamelCase : List[str] = np.shape(A_ ) _lowerCamelCase : List[str] = np.shape(A_ ) if shape_a[0] != shape_b[0]: _lowerCamelCase : Tuple = ( '''Expected the same number of rows for A and B. ''' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(A_ ) if shape_b[1] != shape_c[1]: _lowerCamelCase : Tuple = ( '''Expected the same number of columns for B and C. ''' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(A_ ) _lowerCamelCase : List[str] = pseudo_inv if a_inv is None: try: _lowerCamelCase : Any = np.linalg.inv(A_ ) except np.linalg.LinAlgError: raise ValueError( '''Input matrix A is not invertible. Cannot compute Schur complement.''' ) return mat_c - mat_b.T @ a_inv @ mat_b class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _lowerCamelCase : List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) _lowerCamelCase : List[str] = np.array([[2, 1], [6, 3]] ) _lowerCamelCase : List[Any] = schur_complement(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Dict = np.block([[a, b], [b.T, c]] ) _lowerCamelCase : Tuple = np.linalg.det(__lowerCAmelCase ) _lowerCamelCase : List[str] = np.linalg.det(__lowerCAmelCase ) _lowerCamelCase : Any = np.linalg.det(__lowerCAmelCase ) self.assertAlmostEqual(__lowerCAmelCase , det_a * det_s ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _lowerCamelCase : Optional[int] = np.array([[0, 3], [3, 0], [2, 3]] ) _lowerCamelCase : int = np.array([[2, 1], [6, 3]] ) with self.assertRaises(__lowerCAmelCase ): schur_complement(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : str = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _lowerCamelCase : List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) _lowerCamelCase : Union[str, Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(__lowerCAmelCase ): schur_complement(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
72
0
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } _lowerCamelCase : int = { """vocab_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json""" }, """merges_file""": { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt""" }, """tokenizer_config_file""": { """facebook/blenderbot_small-90M""": ( """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json""" ) }, } _lowerCamelCase : Union[str, Any] = { """facebook/blenderbot_small-90M""": 512, } class UpperCamelCase_ ( _lowercase ): '''simple docstring''' UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = BlenderbotSmallTokenizer def __init__( self : List[str] , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : str="<|endoftext|>" , UpperCAmelCase__ : List[Any]="<|endoftext|>" , UpperCAmelCase__ : Optional[Any]="<|endoftext|>" , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : str=True , **UpperCAmelCase__ : List[str] , ) ->Tuple: '''simple docstring''' super().__init__( ByteLevelBPETokenizer( vocab=__lowerCAmelCase , merges=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase , trim_offsets=__lowerCAmelCase , ) , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , **__lowerCAmelCase , ) A__ = add_prefix_space def SCREAMING_SNAKE_CASE ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str]=None) ->Dict: '''simple docstring''' A__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None) ->Union[str, Any]: '''simple docstring''' A__ = [self.sep_token_id] A__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
14
"""simple docstring""" def snake_case_ ( A_ : list[int], A_ : str ): '''simple docstring''' _lowerCamelCase : Tuple = int(A_ ) # Initialize Result _lowerCamelCase : Dict = [] # Traverse through all denomination for denomination in reversed(A_ ): # Find denominations while int(A_ ) >= int(A_ ): total_value -= int(A_ ) answer.append(A_ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": lowerCAmelCase__ = [] lowerCAmelCase__ = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): lowerCAmelCase__ = int(input('''Enter the number of denominations you want to add: ''').strip()) for i in range(0, n): denominations.append(int(input(F"""Denomination {i}: """).strip())) lowerCAmelCase__ = input('''Enter the change you want to make in Indian Currency: ''').strip() else: # All denominations of Indian Currency if user does not enter lowerCAmelCase__ = [1, 2, 5, 10, 20, 50, 100, 500, 2000] lowerCAmelCase__ = input('''Enter the change you want to make: ''').strip() if int(value) == 0 or int(value) < 0: print('''The total value cannot be zero or negative.''') else: print(F"""Following is minimal change for {value}: """) lowerCAmelCase__ = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
72
0
'''simple docstring''' import os def __UpperCamelCase ( ): '''simple docstring''' __lowercase =os.path.dirname(os.path.realpath(A_ ) ) __lowercase =os.path.join(A_, 'triangle.txt' ) with open(A_ ) as f: __lowercase =f.readlines() __lowercase =[] for line in triangle: __lowercase =[] for number in line.strip().split(' ' ): numbers_from_line.append(int(A_ ) ) a.append(A_ ) for i in range(1, len(A_ ) ): for j in range(len(a[i] ) ): __lowercase =a[i - 1][j] if j != len(a[i - 1] ) else 0 __lowercase =a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(A_, A_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
141
"""simple docstring""" def snake_case_ ( A_ : int = 2_00_00_00 ): '''simple docstring''' _lowerCamelCase : int = [0 for i in range(n + 1 )] _lowerCamelCase : List[str] = 1 _lowerCamelCase : Any = 1 for i in range(2, int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i, n + 1, A_ ): _lowerCamelCase : str = 1 _lowerCamelCase : Tuple = 0 for i in range(A_ ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(F"""{solution() = }""")
72
0
'''simple docstring''' import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) UpperCamelCase__ = { '''sample_size''': 3_2, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': 1_0_0_0, '''block_out_channels''': [3_2, 6_4], '''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''', } UpperCamelCase__ = { '''sample_size''': 6_4, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 3, '''num_class_embeds''': 1_0_0_0, '''block_out_channels''': [1_9_2, 1_9_2 * 2, 1_9_2 * 3, 1_9_2 * 4], '''attention_head_dim''': 6_4, '''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''', } UpperCamelCase__ = { '''sample_size''': 2_5_6, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': None, '''block_out_channels''': [2_5_6, 2_5_6, 2_5_6 * 2, 2_5_6 * 2, 2_5_6 * 4, 2_5_6 * 4], '''attention_head_dim''': 6_4, '''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''', } UpperCamelCase__ = { '''num_train_timesteps''': 4_0, '''sigma_min''': 0.002, '''sigma_max''': 8_0.0, } UpperCamelCase__ = { '''num_train_timesteps''': 2_0_1, '''sigma_min''': 0.002, '''sigma_max''': 8_0.0, } UpperCamelCase__ = { '''num_train_timesteps''': 1_5_1, '''sigma_min''': 0.002, '''sigma_max''': 8_0.0, } def a__ ( lowerCAmelCase__ ) -> int: 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 a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ) -> Optional[int]: UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.in_layers.0.weight"""] UpperCAmelCase__ : List[str] = checkpoint[F"""{old_prefix}.in_layers.0.bias"""] UpperCAmelCase__ : Tuple = checkpoint[F"""{old_prefix}.in_layers.2.weight"""] UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.in_layers.2.bias"""] UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.emb_layers.1.weight"""] UpperCAmelCase__ : Tuple = checkpoint[F"""{old_prefix}.emb_layers.1.bias"""] UpperCAmelCase__ : Optional[Any] = checkpoint[F"""{old_prefix}.out_layers.0.weight"""] UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.out_layers.0.bias"""] UpperCAmelCase__ : List[Any] = checkpoint[F"""{old_prefix}.out_layers.3.weight"""] UpperCAmelCase__ : Any = checkpoint[F"""{old_prefix}.out_layers.3.bias"""] if has_skip: UpperCAmelCase__ : Dict = checkpoint[F"""{old_prefix}.skip_connection.weight"""] UpperCAmelCase__ : int = checkpoint[F"""{old_prefix}.skip_connection.bias"""] return new_checkpoint def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None ) -> Optional[Any]: UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 ) UpperCAmelCase__ : str = checkpoint[F"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 ) UpperCAmelCase__ : Union[str, Any] = checkpoint[F"""{old_prefix}.norm.weight"""] UpperCAmelCase__ : Optional[int] = checkpoint[F"""{old_prefix}.norm.bias"""] UpperCAmelCase__ : Union[str, Any] = weight_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : List[Any] = bias_q.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : List[Any] = weight_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Any = bias_k.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : Union[str, Any] = weight_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : List[Any] = bias_v.squeeze(-1 ).squeeze(-1 ) UpperCAmelCase__ : List[Any] = ( checkpoint[F"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 ) ) UpperCAmelCase__ : Tuple = checkpoint[F"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: UpperCAmelCase__ : Union[str, Any] = torch.load(A_ , map_location='''cpu''' ) UpperCAmelCase__ : Dict = {} UpperCAmelCase__ : List[str] = checkpoint['''time_embed.0.weight'''] UpperCAmelCase__ : Union[str, Any] = checkpoint['''time_embed.0.bias'''] UpperCAmelCase__ : List[str] = checkpoint['''time_embed.2.weight'''] UpperCAmelCase__ : Union[str, Any] = checkpoint['''time_embed.2.bias'''] if unet_config["num_class_embeds"] is not None: UpperCAmelCase__ : List[str] = checkpoint['''label_emb.weight'''] UpperCAmelCase__ : Any = checkpoint['''input_blocks.0.0.weight'''] UpperCAmelCase__ : Union[str, Any] = checkpoint['''input_blocks.0.0.bias'''] UpperCAmelCase__ : Tuple = unet_config['''down_block_types'''] UpperCAmelCase__ : Tuple = unet_config['''layers_per_block'''] UpperCAmelCase__ : List[Any] = unet_config['''attention_head_dim'''] UpperCAmelCase__ : str = unet_config['''block_out_channels'''] UpperCAmelCase__ : Dict = 1 UpperCAmelCase__ : str = channels_list[0] for i, layer_type in enumerate(A_ ): UpperCAmelCase__ : str = channels_list[i] UpperCAmelCase__ : str = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(A_ ): UpperCAmelCase__ : Union[str, Any] = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Tuple = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : List[Any] = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Tuple = convert_resnet(A_ , A_ , A_ , A_ , has_skip=A_ ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(A_ ): UpperCAmelCase__ : List[Any] = F"""down_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : List[Any] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : Optional[int] = True if j == 0 and downsample_block_has_skip else False UpperCAmelCase__ : Dict = convert_resnet(A_ , A_ , A_ , A_ , has_skip=A_ ) UpperCAmelCase__ : str = F"""down_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : Any = F"""input_blocks.{current_layer}.1""" UpperCAmelCase__ : str = convert_attention( A_ , A_ , A_ , A_ , A_ ) current_layer += 1 if i != len(A_ ) - 1: UpperCAmelCase__ : List[Any] = F"""down_blocks.{i}.downsamplers.0""" UpperCAmelCase__ : List[str] = F"""input_blocks.{current_layer}.0""" UpperCAmelCase__ : str = convert_resnet(A_ , A_ , A_ , A_ ) current_layer += 1 UpperCAmelCase__ : Tuple = current_channels # hardcoded the mid-block for now UpperCAmelCase__ : Tuple = '''mid_block.resnets.0''' UpperCAmelCase__ : int = '''middle_block.0''' UpperCAmelCase__ : List[str] = convert_resnet(A_ , A_ , A_ , A_ ) UpperCAmelCase__ : List[str] = '''mid_block.attentions.0''' UpperCAmelCase__ : Any = '''middle_block.1''' UpperCAmelCase__ : List[Any] = convert_attention(A_ , A_ , A_ , A_ , A_ ) UpperCAmelCase__ : Tuple = '''mid_block.resnets.1''' UpperCAmelCase__ : Tuple = '''middle_block.2''' UpperCAmelCase__ : Dict = convert_resnet(A_ , A_ , A_ , A_ ) UpperCAmelCase__ : Optional[int] = 0 UpperCAmelCase__ : str = unet_config['''up_block_types'''] for i, layer_type in enumerate(A_ ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Dict = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Union[str, Any] = convert_resnet(A_ , A_ , A_ , A_ , has_skip=A_ ) current_layer += 1 if i != len(A_ ) - 1: UpperCAmelCase__ : Tuple = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : Dict = F"""output_blocks.{current_layer-1}.1""" UpperCAmelCase__ : Tuple = convert_resnet(A_ , A_ , A_ , A_ ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): UpperCAmelCase__ : Any = F"""up_blocks.{i}.resnets.{j}""" UpperCAmelCase__ : Optional[Any] = F"""output_blocks.{current_layer}.0""" UpperCAmelCase__ : Tuple = convert_resnet(A_ , A_ , A_ , A_ , has_skip=A_ ) UpperCAmelCase__ : List[str] = F"""up_blocks.{i}.attentions.{j}""" UpperCAmelCase__ : Optional[int] = F"""output_blocks.{current_layer}.1""" UpperCAmelCase__ : int = convert_attention( A_ , A_ , A_ , A_ , A_ ) current_layer += 1 if i != len(A_ ) - 1: UpperCAmelCase__ : Optional[int] = F"""up_blocks.{i}.upsamplers.0""" UpperCAmelCase__ : Tuple = F"""output_blocks.{current_layer-1}.2""" UpperCAmelCase__ : Any = convert_resnet(A_ , A_ , A_ , A_ ) UpperCAmelCase__ : Optional[int] = checkpoint['''out.0.weight'''] UpperCAmelCase__ : int = checkpoint['''out.0.bias'''] UpperCAmelCase__ : Union[str, Any] = checkpoint['''out.2.weight'''] UpperCAmelCase__ : Optional[int] = checkpoint['''out.2.bias'''] return new_checkpoint if __name__ == "__main__": UpperCamelCase__ = 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.''') UpperCamelCase__ = parser.parse_args() UpperCamelCase__ = strabool(args.class_cond) UpperCamelCase__ = os.path.basename(args.unet_path) print(F"""Checkpoint: {ckpt_name}""") # Get U-Net config if "imagenet64" in ckpt_name: UpperCamelCase__ = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): UpperCamelCase__ = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: UpperCamelCase__ = TEST_UNET_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") if not args.class_cond: UpperCamelCase__ = None UpperCamelCase__ = con_pt_to_diffuser(args.unet_path, unet_config) UpperCamelCase__ = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: UpperCamelCase__ = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: UpperCamelCase__ = 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)): UpperCamelCase__ = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") UpperCamelCase__ = CMStochasticIterativeScheduler(**scheduler_config) UpperCamelCase__ = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
181
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def snake_case_ ( A_ : Any ): '''simple docstring''' _lowerCamelCase : Any = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A_, A_ ) def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' _lowerCamelCase , _lowerCamelCase : Tuple = emb.weight.shape _lowerCamelCase : Dict = nn.Linear(A_, A_, bias=A_ ) _lowerCamelCase : str = emb.weight.data return lin_layer def snake_case_ ( A_ : str, A_ : Optional[int]="facebook/mbart-large-en-ro", A_ : Union[str, Any]=False, A_ : List[str]=False ): '''simple docstring''' _lowerCamelCase : Tuple = torch.load(A_, map_location='''cpu''' )['''model'''] remove_ignore_keys_(A_ ) _lowerCamelCase : int = state_dict['''encoder.embed_tokens.weight'''].shape[0] _lowerCamelCase : Any = MBartConfig.from_pretrained(A_, vocab_size=A_ ) if mbart_aa and finetuned: _lowerCamelCase : Any = '''relu''' _lowerCamelCase : Optional[int] = state_dict['''decoder.embed_tokens.weight'''] _lowerCamelCase : Any = MBartForConditionalGeneration(A_ ) model.model.load_state_dict(A_ ) if finetuned: _lowerCamelCase : str = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
72
0
'''simple docstring''' from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def UpperCAmelCase_ ( __lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): if version.parse(hfh.__version__ ).release < version.parse("0.11.0" ).release: # old versions of hfh don't url-encode the file path lowercase_ :Optional[Any] = quote(A_ ) return hfh.hf_hub_url(A_ ,A_ ,repo_type="dataset" ,revision=A_ )
223
"""simple docstring""" def snake_case_ ( A_ : list[list] ): '''simple docstring''' _lowerCamelCase : Optional[int] = current_set.copy() for row_index, row in enumerate(A_ ): _lowerCamelCase : Tuple = row[0] for column_index, column in enumerate(A_ ): if magnitude == 0: _lowerCamelCase : List[Any] = column continue _lowerCamelCase : List[Any] = column / magnitude # Subtract to cancel term _lowerCamelCase : Union[str, Any] = current_set[0] _lowerCamelCase : Dict = [first_row] _lowerCamelCase : str = current_set[1::] for row in current_set: _lowerCamelCase : Union[str, Any] = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(A_ ) continue for column_index in range(len(A_ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(A_ ) # Create next recursion iteration set if len(final_set[0] ) != 3: _lowerCamelCase : Any = final_set[0] _lowerCamelCase : Any = [] _lowerCamelCase : Optional[int] = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) _lowerCamelCase : Dict = simplify(A_ ) for i in range(len(A_ ) ): resultant[i].insert(0, current_first_column[i] ) resultant.insert(0, A_ ) _lowerCamelCase : Tuple = resultant return final_set def snake_case_ ( A_ : list[list] ): '''simple docstring''' if len(A_ ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) _lowerCamelCase : Dict = len(A_ ) + 1 if any(len(A_ ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(A_, (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(A_ ) == 1: return [equations[0][-1] / equations[0][0]] _lowerCamelCase : Optional[Any] = equations.copy() if any(0 in row for row in data_set ): _lowerCamelCase : str = data_set.copy() _lowerCamelCase : List[Any] = [] for row_index, row in enumerate(A_ ): if 0 not in row: _lowerCamelCase : Union[str, Any] = data_set.pop(A_ ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0, A_ ) _lowerCamelCase : List[str] = data_set.copy() _lowerCamelCase : int = simplify(A_ ) _lowerCamelCase : int = simplified[::-1] _lowerCamelCase : list = [] for row in simplified: _lowerCamelCase : Tuple = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue _lowerCamelCase : Optional[Any] = row.copy()[: len(A_ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(A_ ) == 0: solutions.append(0 ) continue _lowerCamelCase : Tuple = temp_row[1::] _lowerCamelCase : Tuple = temp_row[::-1] for column_index, column in enumerate(A_ ): current_solution -= column * solutions[column_index] solutions.append(A_ ) _lowerCamelCase : Optional[int] = [] for item in solutions: final.append(float(round(A_, 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
72
0
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCAmelCase ( _lowercase): __a : Optional[int] = (DDPMParallelScheduler,) def __snake_case ( self , **_A ) -> List[Any]: '''simple docstring''' _UpperCAmelCase : Tuple = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**__lowerCAmelCase ) return config def __snake_case ( self ) -> int: '''simple docstring''' for timesteps in [1, 5, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__lowerCAmelCase ) def __snake_case ( self ) -> Any: '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__lowerCAmelCase , beta_end=__lowerCAmelCase ) def __snake_case ( self ) -> Tuple: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__lowerCAmelCase ) def __snake_case ( self ) -> Dict: '''simple docstring''' for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=__lowerCAmelCase ) def __snake_case ( self ) -> Optional[Any]: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=__lowerCAmelCase ) def __snake_case ( self ) -> str: '''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 __snake_case ( self ) -> Union[str, Any]: '''simple docstring''' for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=__lowerCAmelCase ) def __snake_case ( self ) -> str: '''simple docstring''' for t in [0, 5_00, 9_99]: self.check_over_forward(time_step=__lowerCAmelCase ) def __snake_case ( self ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : Dict = self.scheduler_classes[0] _UpperCAmelCase : Dict = self.get_scheduler_config() _UpperCAmelCase : Union[str, 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_87 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 ) - 0.02 ) ) < 1e-5 def __snake_case ( self ) -> str: '''simple docstring''' _UpperCAmelCase : List[Any] = self.scheduler_classes[0] _UpperCAmelCase : List[str] = self.get_scheduler_config() _UpperCAmelCase : Optional[Any] = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : Dict = len(__lowerCAmelCase ) _UpperCAmelCase : Tuple = self.dummy_model() _UpperCAmelCase : Any = self.dummy_sample_deter _UpperCAmelCase : Union[str, Any] = self.dummy_sample_deter + 0.1 _UpperCAmelCase : Any = self.dummy_sample_deter - 0.1 _UpperCAmelCase : Union[str, Any] = samplea.shape[0] _UpperCAmelCase : List[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) _UpperCAmelCase : str = torch.arange(__lowerCAmelCase )[0:3, None].repeat(1 , __lowerCAmelCase ) _UpperCAmelCase : Optional[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _UpperCAmelCase : str = scheduler.batch_step_no_noise(__lowerCAmelCase , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) _UpperCAmelCase : Optional[int] = torch.sum(torch.abs(__lowerCAmelCase ) ) _UpperCAmelCase : Optional[Any] = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 11_53.18_33 ) < 1e-2 assert abs(result_mean.item() - 0.5005 ) < 1e-3 def __snake_case ( self ) -> Any: '''simple docstring''' _UpperCAmelCase : List[str] = self.scheduler_classes[0] _UpperCAmelCase : Optional[Any] = self.get_scheduler_config() _UpperCAmelCase : int = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : Union[str, Any] = len(__lowerCAmelCase ) _UpperCAmelCase : int = self.dummy_model() _UpperCAmelCase : Tuple = self.dummy_sample_deter _UpperCAmelCase : int = torch.manual_seed(0 ) for t in reversed(range(__lowerCAmelCase ) ): # 1. predict noise residual _UpperCAmelCase : Tuple = model(__lowerCAmelCase , __lowerCAmelCase ) # 2. predict previous mean of sample x_t-1 _UpperCAmelCase : Dict = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample _UpperCAmelCase : Union[str, Any] = pred_prev_sample _UpperCAmelCase : Optional[int] = torch.sum(torch.abs(__lowerCAmelCase ) ) _UpperCAmelCase : Optional[Any] = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 2_58.96_06 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __snake_case ( self ) -> Dict: '''simple docstring''' _UpperCAmelCase : Tuple = self.scheduler_classes[0] _UpperCAmelCase : Union[str, Any] = self.get_scheduler_config(prediction_type="""v_prediction""" ) _UpperCAmelCase : int = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : Optional[int] = len(__lowerCAmelCase ) _UpperCAmelCase : Any = self.dummy_model() _UpperCAmelCase : int = self.dummy_sample_deter _UpperCAmelCase : List[str] = torch.manual_seed(0 ) for t in reversed(range(__lowerCAmelCase ) ): # 1. predict noise residual _UpperCAmelCase : List[str] = model(__lowerCAmelCase , __lowerCAmelCase ) # 2. predict previous mean of sample x_t-1 _UpperCAmelCase : Optional[int] = scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample _UpperCAmelCase : Optional[int] = pred_prev_sample _UpperCAmelCase : Optional[Any] = torch.sum(torch.abs(__lowerCAmelCase ) ) _UpperCAmelCase : List[Any] = torch.mean(torch.abs(__lowerCAmelCase ) ) assert abs(result_sum.item() - 2_02.02_96 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __snake_case ( self ) -> Dict: '''simple docstring''' _UpperCAmelCase : int = self.scheduler_classes[0] _UpperCAmelCase : Dict = self.get_scheduler_config() _UpperCAmelCase : Optional[int] = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : Optional[Any] = [1_00, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=__lowerCAmelCase ) _UpperCAmelCase : Tuple = scheduler.timesteps for i, timestep in enumerate(__lowerCAmelCase ): if i == len(__lowerCAmelCase ) - 1: _UpperCAmelCase : str = -1 else: _UpperCAmelCase : List[Any] = timesteps[i + 1] _UpperCAmelCase : Optional[Any] = scheduler.previous_timestep(__lowerCAmelCase ) _UpperCAmelCase : Tuple = prev_t.item() self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def __snake_case ( self ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : Any = self.scheduler_classes[0] _UpperCAmelCase : int = self.get_scheduler_config() _UpperCAmelCase : Any = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : int = [1_00, 87, 50, 51, 0] with self.assertRaises(__lowerCAmelCase , msg="""`custom_timesteps` must be in descending order.""" ): scheduler.set_timesteps(timesteps=__lowerCAmelCase ) def __snake_case ( self ) -> Tuple: '''simple docstring''' _UpperCAmelCase : Optional[Any] = self.scheduler_classes[0] _UpperCAmelCase : Optional[Any] = self.get_scheduler_config() _UpperCAmelCase : Optional[Any] = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : Tuple = [1_00, 87, 50, 1, 0] _UpperCAmelCase : Dict = 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 __snake_case ( self ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : int = self.scheduler_classes[0] _UpperCAmelCase : str = self.get_scheduler_config() _UpperCAmelCase : List[str] = scheduler_class(**__lowerCAmelCase ) _UpperCAmelCase : Tuple = [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 )
246
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __snake_case ( _lowercase): snake_case__ : List[Any] = "Speech2TextFeatureExtractor" snake_case__ : Union[str, Any] = "Speech2TextTokenizer" def __init__( self : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" super().__init__(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : List[str] = self.feature_extractor _lowerCamelCase : str = False def __call__( self : List[Any] , *__lowerCAmelCase : int , **__lowerCAmelCase : List[str] ): """simple docstring""" if self._in_target_context_manager: return self.current_processor(*__lowerCAmelCase , **__lowerCAmelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) _lowerCamelCase : str = kwargs.pop('''raw_speech''' ) else: _lowerCamelCase : Tuple = kwargs.pop('''audio''' , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = kwargs.pop('''sampling_rate''' , __lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = kwargs.pop('''text''' , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: _lowerCamelCase : List[Any] = args[0] _lowerCamelCase : int = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: _lowerCamelCase : List[Any] = self.feature_extractor(__lowerCAmelCase , *__lowerCAmelCase , sampling_rate=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None: _lowerCamelCase : List[Any] = self.tokenizer(__lowerCAmelCase , **__lowerCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: _lowerCamelCase : List[str] = encodings['''input_ids'''] return inputs def SCREAMING_SNAKE_CASE ( self : Any , *__lowerCAmelCase : List[Any] , **__lowerCAmelCase : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : int ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @contextmanager def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : Any = self.tokenizer yield _lowerCamelCase : List[str] = self.feature_extractor _lowerCamelCase : Tuple = False
72
0
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) __A = [ "cross_validation.py", "gradient_accumulation.py", "local_sgd.py", "multi_process_metrics.py", "memory.py", "automatic_gradient_accumulation.py", "fsdp_with_peak_mem_tracking.py", "deepspeed_with_config_support.py", "megatron_lm_gpt_pretraining.py", ] class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool , UpperCAmelCase_ : str = None , UpperCAmelCase_ : list = None) ->Dict: '''simple docstring''' lowerCamelCase__: str =None lowerCamelCase__: Tuple =os.path.abspath(os.path.join("examples" , "by_feature")) lowerCamelCase__: List[Any] =os.path.abspath("examples") for item in os.listdir(__lowerCAmelCase): if item not in EXCLUDE_EXAMPLES: lowerCamelCase__: Optional[int] =os.path.join(__lowerCAmelCase , __lowerCAmelCase) if os.path.isfile(__lowerCAmelCase) and ".py" in item_path: with self.subTest( tested_script=__lowerCAmelCase , feature_script=__lowerCAmelCase , tested_section="main()" if parser_only else "training_function()" , ): lowerCamelCase__: Tuple =compare_against_test( os.path.join(__lowerCAmelCase , __lowerCAmelCase) , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase) lowerCamelCase__: Union[str, Any] ='''\n'''.join(__lowerCAmelCase) if special_strings is not None: for string in special_strings: lowerCamelCase__: Dict =diff.replace(__lowerCAmelCase , "") self.assertEqual(__lowerCAmelCase , "") def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[int]: '''simple docstring''' self.one_complete_example("complete_nlp_example.py" , __lowerCAmelCase) self.one_complete_example("complete_nlp_example.py" , __lowerCAmelCase) def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[Any] =os.path.abspath(os.path.join("examples" , "cv_example.py")) lowerCamelCase__: List[Any] =[ ''' ''' * 16 + '''{\n\n''', ''' ''' * 20 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 20 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 20 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 20 + '''"epoch": epoch,\n\n''', ''' ''' * 16 + '''},\n\n''', ''' ''' * 16 + '''step=epoch,\n''', ''' ''' * 12, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example("complete_cv_example.py" , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase) self.one_complete_example("complete_cv_example.py" , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class _SCREAMING_SNAKE_CASE ( _lowercase ): '''simple docstring''' lowercase_ = False @classmethod def SCREAMING_SNAKE_CASE_ (cls : Optional[Any]) ->str: '''simple docstring''' super().setUpClass() lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: List[Any] =os.path.join(cls._tmpdir , "default_config.yml") write_basic_config(save_location=cls.configPath) lowerCamelCase__: int =['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ (cls : List[str]) ->List[str]: '''simple docstring''' super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Dict =F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "epoch_0"))) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Optional[int] =F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() lowerCamelCase__: Any =run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "step_2"))) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0")} """.split() lowerCamelCase__: List[str] =run_command(self._launch_args + testargs , return_stdout=__lowerCAmelCase) self.assertNotIn("epoch 0:" , __lowerCAmelCase) self.assertIn("epoch 1:" , __lowerCAmelCase) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Any =F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2")} """.split() lowerCamelCase__: int =run_command(self._launch_args + testargs , return_stdout=__lowerCAmelCase) if torch.cuda.is_available(): lowerCamelCase__: str =torch.cuda.device_count() else: lowerCamelCase__: List[str] =1 if num_processes > 1: self.assertNotIn("epoch 0:" , __lowerCAmelCase) self.assertIn("epoch 1:" , __lowerCAmelCase) else: self.assertIn("epoch 0:" , __lowerCAmelCase) self.assertIn("epoch 1:" , __lowerCAmelCase) @slow def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[Any] =''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "0"}): lowerCamelCase__: List[str] =run_command(self._launch_args + testargs , return_stdout=__lowerCAmelCase) lowerCamelCase__: int =re.findall("({.+})" , __lowerCAmelCase) lowerCamelCase__: List[str] =[r for r in results if '''accuracy''' in r][-1] lowerCamelCase__: Dict =ast.literal_eval(__lowerCAmelCase) self.assertGreaterEqual(results["accuracy"] , 0.75) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] =['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"}) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: lowerCamelCase__: Tuple =F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(__lowerCAmelCase , "tracking"))) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: Union[str, Any] =['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: int =['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs)
10
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = {'''configuration_reformer''': ['''REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ReformerConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''ReformerTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''ReformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ReformerAttention''', '''ReformerForMaskedLM''', '''ReformerForQuestionAnswering''', '''ReformerForSequenceClassification''', '''ReformerLayer''', '''ReformerModel''', '''ReformerModelWithLMHead''', '''ReformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
0
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCamelCase_ ( UpperCamelCase__ : Any , UpperCamelCase__ : str , UpperCamelCase__ : int ) -> Any: """simple docstring""" __lowerCamelCase = hf_hub_url(repo_id=A_ , path=A_ , revision=A_ ) assert url == F"""https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(A_ )}"""
90
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { '''configuration_autoformer''': [ '''AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AutoformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AutoformerForPrediction''', '''AutoformerModel''', '''AutoformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
0
from __future__ import annotations class SCREAMING_SNAKE_CASE__ : def __init__( self,__lowerCamelCase,__lowerCamelCase ): A__ = text, pattern A__ = len(__lowerCAmelCase ), len(__lowerCAmelCase ) def UpperCamelCase ( self,__lowerCamelCase ): for i in range(self.patLen - 1,-1,-1 ): if char == self.pattern[i]: return i return -1 def UpperCamelCase ( self,__lowerCamelCase ): for i in range(self.patLen - 1,-1,-1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def UpperCamelCase ( self ): A__ = [] for i in range(self.textLen - self.patLen + 1 ): A__ = self.mismatch_in_text(__lowerCAmelCase ) if mismatch_index == -1: positions.append(__lowerCAmelCase ) else: A__ = self.match_in_pattern(self.text[mismatch_index] ) A__ = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions a__: Any = 'ABAABA' a__: int = 'AB' a__: List[str] = BoyerMooreSearch(text, pattern) a__: List[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
193
"""simple docstring""" import math def snake_case_ ( A_ : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(A_ ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def snake_case_ ( A_ : float = 0.1 ): '''simple docstring''' _lowerCamelCase : Optional[int] = 3 _lowerCamelCase : List[str] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1 ): primes += is_prime(A_ ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
72
0
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent _a = {'''UserAgent''': UserAgent().random} def _a ( SCREAMING_SNAKE_CASE : str ) -> int: """simple docstring""" __lowerCAmelCase: Tuple = script.contents[0] __lowerCAmelCase: Optional[Any] = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class A_ : def __init__( self : str , UpperCAmelCase : List[Any] ) -> Optional[Any]: __lowerCAmelCase: Union[str, Any] = F'''https://www.instagram.com/{username}/''' __lowerCAmelCase: Optional[int] = self.get_json() def UpperCAmelCase ( self : Dict ) -> Optional[Any]: __lowerCAmelCase: str = requests.get(self.url , headers=__lowerCAmelCase ).text __lowerCAmelCase: List[str] = BeautifulSoup(__lowerCAmelCase , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Tuple ) -> Tuple: return F'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self : Any ) -> Optional[Any]: return F'''{self.fullname} ({self.username}) is {self.biography}''' @property def UpperCAmelCase ( self : str ) -> Tuple: return self.user_data["username"] @property def UpperCAmelCase ( self : List[str] ) -> Any: return self.user_data["full_name"] @property def UpperCAmelCase ( self : Optional[Any] ) -> Tuple: return self.user_data["biography"] @property def UpperCAmelCase ( self : int ) -> Optional[Any]: return self.user_data["business_email"] @property def UpperCAmelCase ( self : List[str] ) -> Optional[Any]: return self.user_data["external_url"] @property def UpperCAmelCase ( self : Union[str, Any] ) -> Dict: return self.user_data["edge_followed_by"]["count"] @property def UpperCAmelCase ( self : str ) -> int: return self.user_data["edge_follow"]["count"] @property def UpperCAmelCase ( self : Dict ) -> Tuple: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def UpperCAmelCase ( self : Dict ) -> Tuple: return self.user_data["profile_pic_url_hd"] @property def UpperCAmelCase ( self : List[str] ) -> Optional[int]: return self.user_data["is_verified"] @property def UpperCAmelCase ( self : List[str] ) -> Dict: return self.user_data["is_private"] def _a ( SCREAMING_SNAKE_CASE : str = "github" ) -> Any: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions __lowerCAmelCase: List[Any] = InstagramUser(A_ ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , A_ ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() _a = InstagramUser('''github''') print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
322
"""simple docstring""" import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) _lowerCamelCase : Union[str, Any] = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(__lowerCAmelCase ) _lowerCamelCase : Tuple = -1 _lowerCamelCase : List[Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = model.generate(__lowerCAmelCase , max_new_tokens=1_0 , do_sample=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: _lowerCamelCase : Union[str, Any] = TextStreamer(__lowerCAmelCase ) model.generate(__lowerCAmelCase , max_new_tokens=1_0 , do_sample=__lowerCAmelCase , streamer=__lowerCAmelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _lowerCamelCase : int = cs.out[:-1] self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) _lowerCamelCase : Optional[int] = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(__lowerCAmelCase ) _lowerCamelCase : Tuple = -1 _lowerCamelCase : List[Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = model.generate(__lowerCAmelCase , max_new_tokens=1_0 , do_sample=__lowerCAmelCase ) _lowerCamelCase : List[str] = tokenizer.decode(greedy_ids[0] ) _lowerCamelCase : Tuple = TextIteratorStreamer(__lowerCAmelCase ) _lowerCamelCase : Tuple = {'''input_ids''': input_ids, '''max_new_tokens''': 1_0, '''do_sample''': False, '''streamer''': streamer} _lowerCamelCase : List[Any] = Thread(target=model.generate , kwargs=__lowerCAmelCase ) thread.start() _lowerCamelCase : int = '''''' for new_text in streamer: streamer_text += new_text self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Dict = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) _lowerCamelCase : str = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(__lowerCAmelCase ) _lowerCamelCase : Tuple = -1 _lowerCamelCase : Optional[Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCAmelCase ) _lowerCamelCase : int = model.generate(__lowerCAmelCase , max_new_tokens=1_0 , do_sample=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = greedy_ids[:, input_ids.shape[1] :] _lowerCamelCase : int = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: _lowerCamelCase : Any = TextStreamer(__lowerCAmelCase , skip_prompt=__lowerCAmelCase ) model.generate(__lowerCAmelCase , max_new_tokens=1_0 , do_sample=__lowerCAmelCase , streamer=__lowerCAmelCase ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer _lowerCamelCase : Union[str, Any] = cs.out[:-1] self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained('''distilgpt2''' ) _lowerCamelCase : Optional[Any] = AutoModelForCausalLM.from_pretrained('''distilgpt2''' ).to(__lowerCAmelCase ) _lowerCamelCase : str = -1 _lowerCamelCase : Any = torch.ones((1, 5) , device=__lowerCAmelCase ).long() * model.config.bos_token_id with CaptureStdout() as cs: _lowerCamelCase : List[Any] = TextStreamer(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase ) model.generate(__lowerCAmelCase , max_new_tokens=1 , do_sample=__lowerCAmelCase , streamer=__lowerCAmelCase ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token _lowerCamelCase : Any = cs.out[:-1] # Remove the final "\n" _lowerCamelCase : int = tokenizer(__lowerCAmelCase , return_tensors='''pt''' ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) _lowerCamelCase : Dict = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = -1 _lowerCamelCase : Any = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__lowerCAmelCase ) _lowerCamelCase : List[str] = TextIteratorStreamer(__lowerCAmelCase , timeout=0.0_01 ) _lowerCamelCase : str = {'''input_ids''': input_ids, '''max_new_tokens''': 1_0, '''do_sample''': False, '''streamer''': streamer} _lowerCamelCase : List[Any] = Thread(target=model.generate , kwargs=__lowerCAmelCase ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Optional[Any] = '''''' for new_text in streamer: streamer_text += new_text
72
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __init__( self : Any ,lowercase_ : List[Any] ,lowercase_ : List[str]=7 ,lowercase_ : Union[str, Any]=3 ,lowercase_ : Dict=1_8 ,lowercase_ : str=3_0 ,lowercase_ : Union[str, Any]=4_0_0 ,lowercase_ : int=True ,lowercase_ : Any=None ,lowercase_ : Union[str, Any]=True ,lowercase_ : Union[str, Any]=None ,lowercase_ : Tuple=True ,lowercase_ : List[Any]=[0.4814_5466, 0.457_8275, 0.4082_1073] ,lowercase_ : Optional[Any]=[0.2686_2954, 0.2613_0258, 0.2757_7711] ,lowercase_ : Optional[int]=True ,): lowerCAmelCase__ : Dict = size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} lowerCAmelCase__ : Dict = crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8} lowerCAmelCase__ : Dict = parent lowerCAmelCase__ : List[Any] = batch_size lowerCAmelCase__ : List[Any] = num_channels lowerCAmelCase__ : Optional[Any] = image_size lowerCAmelCase__ : List[Any] = min_resolution lowerCAmelCase__ : Optional[Any] = max_resolution lowerCAmelCase__ : Dict = do_resize lowerCAmelCase__ : List[Any] = size lowerCAmelCase__ : Tuple = do_center_crop lowerCAmelCase__ : List[str] = crop_size lowerCAmelCase__ : Dict = do_normalize lowerCAmelCase__ : Optional[Any] = image_mean lowerCAmelCase__ : Dict = image_std lowerCAmelCase__ : Optional[Any] = do_convert_rgb def __lowerCAmelCase ( self : Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCAmelCase ( self : List[Any] ,lowercase_ : Optional[int]=False ,lowercase_ : Tuple=False ,lowercase_ : Optional[Any]=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: lowerCAmelCase__ : Optional[Any] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_5_5 ,size=(self.num_channels, self.max_resolution, self.max_resolution) ,dtype=np.uinta ) ) else: lowerCAmelCase__ : Union[str, Any] = [] for i in range(self.batch_size ): lowerCAmelCase__ : Dict = np.random.choice(np.arange(self.min_resolution ,self.max_resolution ) ,2 ) image_inputs.append(np.random.randint(2_5_5 ,size=(self.num_channels, width, height) ,dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension lowerCAmelCase__ : Any = [Image.fromarray(np.moveaxis(__lowerCAmelCase ,0 ,-1 ) ) for x in image_inputs] if torchify: lowerCAmelCase__ : List[Any] = [torch.from_numpy(__lowerCAmelCase ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE ( _lowercase , unittest.TestCase ): """simple docstring""" lowercase__ = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : Union[str, Any] ): lowerCAmelCase__ : List[str] = ChineseCLIPImageProcessingTester(self ,do_center_crop=__lowerCAmelCase ) @property def __lowerCAmelCase ( self : Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : Union[str, Any] ): lowerCAmelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_resize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''size''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_center_crop''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''center_crop''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_normalize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''image_mean''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''image_std''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_convert_rgb''' ) ) def __lowerCAmelCase ( self : Optional[Any] ): lowerCAmelCase__ : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'''height''': 2_2_4, '''width''': 2_2_4} ) self.assertEqual(image_processor.crop_size ,{'''height''': 1_8, '''width''': 1_8} ) lowerCAmelCase__ : Any = self.image_processing_class.from_dict(self.image_processor_dict ,size=4_2 ,crop_size=8_4 ) self.assertEqual(image_processor.size ,{'''shortest_edge''': 4_2} ) self.assertEqual(image_processor.crop_size ,{'''height''': 8_4, '''width''': 8_4} ) def __lowerCAmelCase ( self : Optional[Any] ): pass def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase ,Image.Image ) # Test not batched input lowerCAmelCase__ : Optional[Any] = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : str = image_processing(__lowerCAmelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCAmelCase ,numpify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase ,np.ndarray ) # Test not batched input lowerCAmelCase__ : Dict = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Optional[int] = image_processing(__lowerCAmelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) def __lowerCAmelCase ( self : Optional[Any] ): lowerCAmelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ : Dict = self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCAmelCase ,torchify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase ,torch.Tensor ) # Test not batched input lowerCAmelCase__ : Dict = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Union[str, Any] = image_processing(__lowerCAmelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) @require_torch @require_vision class SCREAMING_SNAKE_CASE ( _lowercase , unittest.TestCase ): """simple docstring""" lowercase__ = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Any = ChineseCLIPImageProcessingTester(self ,num_channels=4 ,do_center_crop=__lowerCAmelCase ) lowerCAmelCase__ : List[Any] = 3 @property def __lowerCAmelCase ( self : Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_resize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''size''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_center_crop''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''center_crop''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_normalize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''image_mean''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''image_std''' ) ) self.assertTrue(hasattr(__lowerCAmelCase ,'''do_convert_rgb''' ) ) def __lowerCAmelCase ( self : Union[str, Any] ): pass def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ : List[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase ,Image.Image ) # Test not batched input lowerCAmelCase__ : Optional[int] = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,) # Test batched lowerCAmelCase__ : str = image_processing(__lowerCAmelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) ,)
106
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase__ = logging.get_logger(__name__) # TODO: upload to AWS lowerCAmelCase__ = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : int = "retribert" def __init__( self : Optional[int] , __lowerCAmelCase : str=3_0_5_2_2 , __lowerCAmelCase : Tuple=7_6_8 , __lowerCAmelCase : Union[str, Any]=8 , __lowerCAmelCase : Any=1_2 , __lowerCAmelCase : Optional[int]=3_0_7_2 , __lowerCAmelCase : List[str]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : Tuple=5_1_2 , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : Optional[Any]=1E-12 , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any=1_2_8 , __lowerCAmelCase : Optional[int]=0 , **__lowerCAmelCase : str , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Dict = vocab_size _lowerCamelCase : Union[str, Any] = hidden_size _lowerCamelCase : Dict = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : int = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[int] = max_position_embeddings _lowerCamelCase : List[Any] = type_vocab_size _lowerCamelCase : Any = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps _lowerCamelCase : int = share_encoders _lowerCamelCase : Optional[Any] = projection_dim
72
0
'''simple docstring''' from math import factorial def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """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.''', )
37
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : Optional[int] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : str = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] _lowerCamelCase : Optional[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] _lowerCamelCase : Any = '''fp16''' self.assertFalse(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] _lowerCamelCase : str = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] _lowerCamelCase : Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : int = '''fp16''' self.assertFalse(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) )
72
0
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a =""" @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ a ="""\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ a =""" Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: def remove_articles(lowerCamelCase__ ): __lowerCamelCase : Dict = re.compile(R'\b(a|an|the)\b' , re.UNICODE ) return re.sub(lowerCamelCase__ , ' ' , lowerCamelCase__ ) def white_space_fix(lowerCamelCase__ ): return " ".join(text.split() ) def remove_punc(lowerCamelCase__ ): __lowerCamelCase : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: return int(normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: __lowerCamelCase : Union[str, Any] = [any(compute_exact(lowerCamelCase__ , lowerCamelCase__ ) for ref in refs ) for pred, refs in zip(lowerCamelCase__ , lowerCamelCase__ )] return (sum(lowerCamelCase__ ) / len(lowerCamelCase__ )) * 1_0_0 def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = [rgram for rgrams in rgramslist for rgram in rgrams] __lowerCamelCase : Any = Counter(lowerCamelCase__ ) __lowerCamelCase : Optional[int] = Counter(lowerCamelCase__ ) __lowerCamelCase : List[str] = Counter() for sgram, scount in sgramcounter.items(): __lowerCamelCase : Any = scount * numref __lowerCamelCase : Union[str, Any] = Counter(lowerCamelCase__ ) __lowerCamelCase : Optional[int] = Counter() for cgram, ccount in cgramcounter.items(): __lowerCamelCase : List[str] = ccount * numref # KEEP __lowerCamelCase : Optional[Any] = sgramcounter_rep & cgramcounter_rep __lowerCamelCase : List[Any] = keepgramcounter_rep & rgramcounter __lowerCamelCase : int = sgramcounter_rep & rgramcounter __lowerCamelCase : int = 0 __lowerCamelCase : Optional[int] = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __lowerCamelCase : Optional[int] = 1 __lowerCamelCase : Optional[Any] = 1 if len(lowerCamelCase__ ) > 0: __lowerCamelCase : Tuple = keeptmpscorea / len(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __lowerCamelCase : Tuple = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __lowerCamelCase : Dict = 0 if keepscore_precision > 0 or keepscore_recall > 0: __lowerCamelCase : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __lowerCamelCase : str = sgramcounter_rep - cgramcounter_rep __lowerCamelCase : Tuple = delgramcounter_rep - rgramcounter __lowerCamelCase : Tuple = sgramcounter_rep - rgramcounter __lowerCamelCase : Union[str, Any] = 0 __lowerCamelCase : int = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __lowerCamelCase : Any = 1 if len(lowerCamelCase__ ) > 0: __lowerCamelCase : List[Any] = deltmpscorea / len(lowerCamelCase__ ) # ADDITION __lowerCamelCase : str = set(lowerCamelCase__ ) - set(lowerCamelCase__ ) __lowerCamelCase : Optional[int] = set(lowerCamelCase__ ) & set(lowerCamelCase__ ) __lowerCamelCase : str = set(lowerCamelCase__ ) - set(lowerCamelCase__ ) __lowerCamelCase : List[str] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __lowerCamelCase : int = 1 __lowerCamelCase : List[str] = 1 if len(lowerCamelCase__ ) > 0: __lowerCamelCase : Any = addtmpscore / len(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: __lowerCamelCase : Optional[int] = addtmpscore / len(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 if addscore_precision > 0 or addscore_recall > 0: __lowerCamelCase : List[Any] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: __lowerCamelCase : int = len(lowerCamelCase__ ) __lowerCamelCase : int = ssent.split(' ' ) __lowerCamelCase : Optional[Any] = csent.split(' ' ) __lowerCamelCase : int = [] __lowerCamelCase : Union[str, Any] = [] __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : Tuple = [] __lowerCamelCase : str = [] __lowerCamelCase : Optional[int] = [] __lowerCamelCase : List[Any] = [] __lowerCamelCase : List[Any] = [] __lowerCamelCase : Union[str, Any] = [] __lowerCamelCase : Dict = [] for rsent in rsents: __lowerCamelCase : str = rsent.split(' ' ) __lowerCamelCase : List[Any] = [] __lowerCamelCase : List[Any] = [] __lowerCamelCase : Union[str, Any] = [] ragramslist.append(lowerCamelCase__ ) for i in range(0 , len(lowerCamelCase__ ) - 1 ): if i < len(lowerCamelCase__ ) - 1: __lowerCamelCase : List[str] = ragrams[i] + ' ' + ragrams[i + 1] ragrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 2: __lowerCamelCase : List[Any] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] ragrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 3: __lowerCamelCase : List[str] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3] ragrams.append(lowerCamelCase__ ) ragramslist.append(lowerCamelCase__ ) ragramslist.append(lowerCamelCase__ ) ragramslist.append(lowerCamelCase__ ) for i in range(0 , len(lowerCamelCase__ ) - 1 ): if i < len(lowerCamelCase__ ) - 1: __lowerCamelCase : Any = sagrams[i] + ' ' + sagrams[i + 1] sagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 2: __lowerCamelCase : Optional[int] = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] sagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 3: __lowerCamelCase : Any = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3] sagrams.append(lowerCamelCase__ ) for i in range(0 , len(lowerCamelCase__ ) - 1 ): if i < len(lowerCamelCase__ ) - 1: __lowerCamelCase : Any = cagrams[i] + ' ' + cagrams[i + 1] cagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 2: __lowerCamelCase : str = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] cagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 3: __lowerCamelCase : Tuple = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3] cagrams.append(lowerCamelCase__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Dict = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Union[str, Any] = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Union[str, Any] = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : str = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __lowerCamelCase : Optional[int] = sum([delascore, delascore, delascore, delascore] ) / 4 __lowerCamelCase : str = sum([addascore, addascore, addascore, addascore] ) / 4 __lowerCamelCase : List[str] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ = True , lowerCamelCase__ = "13a" , lowerCamelCase__ = True ) -> Any: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: __lowerCamelCase : Optional[Any] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __lowerCamelCase : int = sacrebleu.metrics.bleu._get_tokenizer(lowerCamelCase__ )()(lowerCamelCase__ ) else: __lowerCamelCase : str = sacrebleu.TOKENIZERS[tokenizer]()(lowerCamelCase__ ) elif tokenizer == "moses": __lowerCamelCase : Optional[Any] = sacremoses.MosesTokenizer().tokenize(lowerCamelCase__ , return_str=lowerCamelCase__ , escape=lowerCamelCase__ ) elif tokenizer == "penn": __lowerCamelCase : Tuple = sacremoses.MosesTokenizer().penn_tokenize(lowerCamelCase__ , return_str=lowerCamelCase__ ) else: __lowerCamelCase : List[Any] = sentence if not return_str: __lowerCamelCase : Optional[int] = normalized_sent.split() return normalized_sent def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: if not (len(lowerCamelCase__ ) == len(lowerCamelCase__ ) == len(lowerCamelCase__ )): raise ValueError('Sources length must match predictions and references lengths.' ) __lowerCamelCase : List[str] = 0 for src, pred, refs in zip(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): sari_score += SARIsent(normalize(lowerCamelCase__ ) , normalize(lowerCamelCase__ ) , [normalize(lowerCamelCase__ ) for sent in refs] ) __lowerCamelCase : int = sari_score / len(lowerCamelCase__ ) return 1_0_0 * sari_score def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="exp" , lowerCamelCase__=None , lowerCamelCase__=False , lowerCamelCase__=False , lowerCamelCase__=False , ) -> int: __lowerCamelCase : Tuple = len(references[0] ) if any(len(lowerCamelCase__ ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) __lowerCamelCase : Optional[int] = [[refs[i] for refs in references] for i in range(lowerCamelCase__ )] __lowerCamelCase : Dict = sacrebleu.corpus_bleu( lowerCamelCase__ , lowerCamelCase__ , smooth_method=lowerCamelCase__ , smooth_value=lowerCamelCase__ , force=lowerCamelCase__ , lowercase=lowerCamelCase__ , use_effective_order=lowerCamelCase__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : str): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence'), 'references': datasets.Sequence(datasets.Value('string' ,id='sequence') ,id='references'), }) ,codebase_urls=[ 'https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py', 'https://github.com/cocoxu/simplification/blob/master/SARI.py', 'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py', 'https://github.com/mjpost/sacreBLEU', ] ,reference_urls=[ 'https://www.aclweb.org/anthology/Q16-1029.pdf', 'https://github.com/mjpost/sacreBLEU', 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] ,) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : List[str] = {} result.update({'sari': compute_sari(sources=SCREAMING_SNAKE_CASE__ ,predictions=SCREAMING_SNAKE_CASE__ ,references=SCREAMING_SNAKE_CASE__)}) result.update({'sacrebleu': compute_sacrebleu(predictions=SCREAMING_SNAKE_CASE__ ,references=SCREAMING_SNAKE_CASE__)}) result.update({'exact': compute_em(predictions=SCREAMING_SNAKE_CASE__ ,references=SCREAMING_SNAKE_CASE__)}) return result
73
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
1
from string import ascii_uppercase a ={str(ord(c) - 55): c for c in ascii_uppercase} def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> str: if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('int() can\'t convert non-string with explicit base' ) if num < 0: raise ValueError('parameter must be positive int' ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if base in (0, 1): raise ValueError('base must be >= 2' ) if base > 3_6: raise ValueError('base must be <= 36' ) __lowerCamelCase : List[str] = '' __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[int] = 0 while div != 1: __lowerCamelCase , __lowerCamelCase : List[Any] = divmod(lowerCamelCase__ , lowerCamelCase__ ) if base >= 1_1 and 9 < mod < 3_6: __lowerCamelCase : Optional[int] = ALPHABET_VALUES[str(lowerCamelCase__ )] else: __lowerCamelCase : Optional[Any] = str(lowerCamelCase__ ) new_value += actual_value __lowerCamelCase : Union[str, Any] = num // base __lowerCamelCase : Union[str, Any] = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(lowerCamelCase__ ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
73
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
1
from ..utils import DummyObject, requires_backends class A_ ( metaclass=SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[str] = ['''keras_nlp'''] def __init__( self : Tuple ,*SCREAMING_SNAKE_CASE__ : Any ,**SCREAMING_SNAKE_CASE__ : List[str]): requires_backends(self ,['keras_nlp'])
73
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
1
import numpy as np import datasets a =""" Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] """ a ="""\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } """ a =""" Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {'mahalanobis': array([0.5])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : List[str]): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'X': datasets.Sequence(datasets.Value('float' ,id='sequence') ,id='X'), }) ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): # convert to numpy arrays __lowerCamelCase : Any = np.array(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = np.array(SCREAMING_SNAKE_CASE__) # Assert that arrays are 2D if len(X.shape) != 2: raise ValueError('Expected `X` to be a 2D vector') if len(reference_distribution.shape) != 2: raise ValueError('Expected `reference_distribution` to be a 2D vector') if reference_distribution.shape[0] < 2: raise ValueError( 'Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension') # Get mahalanobis distance for each prediction __lowerCamelCase : str = X - np.mean(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = np.cov(reference_distribution.T) try: __lowerCamelCase : Optional[Any] = np.linalg.inv(SCREAMING_SNAKE_CASE__) except np.linalg.LinAlgError: __lowerCamelCase : int = np.linalg.pinv(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.dot(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = np.dot(SCREAMING_SNAKE_CASE__ ,X_minus_mu.T).diagonal() return {"mahalanobis": mahal_dist}
73
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
1
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL a =logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple[int, int]: def constraint_to_multiple_of(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=0 , lowerCamelCase__=None ): __lowerCamelCase : Dict = round(val / multiple ) * multiple if max_val is not None and x > max_val: __lowerCamelCase : Dict = math.floor(val / multiple ) * multiple if x < min_val: __lowerCamelCase : Optional[int] = math.ceil(val / multiple ) * multiple return x __lowerCamelCase : Tuple = (output_size, output_size) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else output_size __lowerCamelCase , __lowerCamelCase : Optional[Any] = get_image_size(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Tuple = output_size # determine new height and width __lowerCamelCase : Any = output_height / input_height __lowerCamelCase : int = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __lowerCamelCase : str = scale_width else: # fit height __lowerCamelCase : Optional[int] = scale_height __lowerCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCamelCase__ ) __lowerCamelCase : Any = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCamelCase__ ) return (new_height, new_width) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : str = ['''pixel_values'''] def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Dict[str, int] = None ,SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,**SCREAMING_SNAKE_CASE__ : List[str] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = size if size is not None else {'height': 3_8_4, 'width': 3_8_4} __lowerCamelCase : str = get_size_dict(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = do_resize __lowerCamelCase : Optional[Any] = size __lowerCamelCase : Optional[Any] = keep_aspect_ratio __lowerCamelCase : List[Any] = ensure_multiple_of __lowerCamelCase : Any = resample __lowerCamelCase : Union[str, Any] = do_rescale __lowerCamelCase : Tuple = rescale_factor __lowerCamelCase : List[Any] = do_normalize __lowerCamelCase : Optional[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowerCamelCase : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : np.ndarray ,SCREAMING_SNAKE_CASE__ : Dict[str, int] ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None ,**SCREAMING_SNAKE_CASE__ : Any ,): __lowerCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE__) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}") __lowerCamelCase : Tuple = get_resize_output_image_size( SCREAMING_SNAKE_CASE__ ,output_size=(size['height'], size['width']) ,keep_aspect_ratio=SCREAMING_SNAKE_CASE__ ,multiple=SCREAMING_SNAKE_CASE__ ,) return resize(SCREAMING_SNAKE_CASE__ ,size=SCREAMING_SNAKE_CASE__ ,resample=SCREAMING_SNAKE_CASE__ ,data_format=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : np.ndarray ,SCREAMING_SNAKE_CASE__ : Union[int, float] ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): return rescale(SCREAMING_SNAKE_CASE__ ,scale=SCREAMING_SNAKE_CASE__ ,data_format=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : np.ndarray ,SCREAMING_SNAKE_CASE__ : Union[float, List[float]] ,SCREAMING_SNAKE_CASE__ : Union[float, List[float]] ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None ,**SCREAMING_SNAKE_CASE__ : str ,): return normalize(SCREAMING_SNAKE_CASE__ ,mean=SCREAMING_SNAKE_CASE__ ,std=SCREAMING_SNAKE_CASE__ ,data_format=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : ImageInput ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : int = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : int = None ,SCREAMING_SNAKE_CASE__ : PILImageResampling = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST ,**SCREAMING_SNAKE_CASE__ : Union[str, Any] ,): __lowerCamelCase : List[Any] = do_resize if do_resize is not None else self.do_resize __lowerCamelCase : Tuple = size if size is not None else self.size __lowerCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __lowerCamelCase : Dict = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __lowerCamelCase : Optional[int] = resample if resample is not None else self.resample __lowerCamelCase : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale __lowerCamelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCamelCase : int = do_normalize if do_normalize is not None else self.do_normalize __lowerCamelCase : List[Any] = image_mean if image_mean is not None else self.image_mean __lowerCamelCase : Dict = image_std if image_std is not None else self.image_std __lowerCamelCase : Tuple = make_list_of_images(SCREAMING_SNAKE_CASE__) if not valid_images(SCREAMING_SNAKE_CASE__): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __lowerCamelCase : Dict = [to_numpy_array(SCREAMING_SNAKE_CASE__) for image in images] if do_resize: __lowerCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE__ ,size=SCREAMING_SNAKE_CASE__ ,resample=SCREAMING_SNAKE_CASE__) for image in images] if do_rescale: __lowerCamelCase : Union[str, Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ ,scale=SCREAMING_SNAKE_CASE__) for image in images] if do_normalize: __lowerCamelCase : Dict = [self.normalize(image=SCREAMING_SNAKE_CASE__ ,mean=SCREAMING_SNAKE_CASE__ ,std=SCREAMING_SNAKE_CASE__) for image in images] __lowerCamelCase : Optional[int] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) for image in images] __lowerCamelCase : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ ,tensor_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : List[Tuple] = None): __lowerCamelCase : Union[str, Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE__) != len(SCREAMING_SNAKE_CASE__): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits') if is_torch_tensor(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[str] = target_sizes.numpy() __lowerCamelCase : Any = [] for idx in range(len(SCREAMING_SNAKE_CASE__)): __lowerCamelCase : Tuple = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = resized_logits[0].argmax(dim=0) semantic_segmentation.append(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : List[Any] = logits.argmax(dim=1) __lowerCamelCase : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])] return semantic_segmentation
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate a =trt.Logger(trt.Logger.WARNING) a =absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) a =logging.getLogger(__name__) a =argparse.ArgumentParser() # Required parameters parser.add_argument( """--onnx_model_path""", default=None, type=str, required=True, help="""Path to ONNX model: """, ) parser.add_argument( """--output_dir""", default=None, type=str, required=True, help="""The output directory where the model checkpoints and predictions will be written.""", ) # Other parameters parser.add_argument( """--tokenizer_name""", default="""""", type=str, required=True, help="""Pretrained tokenizer name or path if not the same as model_name""", ) parser.add_argument( """--version_2_with_negative""", action="""store_true""", help="""If true, the SQuAD examples contain some that do not have an answer.""", ) parser.add_argument( """--null_score_diff_threshold""", type=float, default=0.0, help="""If null_score - best_non_null is greater than the threshold predict null.""", ) parser.add_argument( """--max_seq_length""", default=384, type=int, help=( """The maximum total input sequence length after WordPiece tokenization. Sequences """ """longer than this will be truncated, and sequences shorter than this will be padded.""" ), ) parser.add_argument( """--doc_stride""", default=128, type=int, help="""When splitting up a long document into chunks, how much stride to take between chunks.""", ) parser.add_argument("""--per_device_eval_batch_size""", default=8, type=int, help="""Batch size per GPU/CPU for evaluation.""") parser.add_argument( """--n_best_size""", default=20, type=int, help="""The total number of n-best predictions to generate in the nbest_predictions.json output file.""", ) parser.add_argument( """--max_answer_length""", default=30, type=int, help=( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ), ) parser.add_argument("""--seed""", type=int, default=42, help="""random seed for initialization""") parser.add_argument( """--dataset_name""", type=str, default=None, required=True, help="""The name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--dataset_config_name""", type=str, default=None, help="""The configuration name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--preprocessing_num_workers""", type=int, default=4, help="""A csv or a json file containing the training data.""" ) parser.add_argument("""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""") parser.add_argument( """--fp16""", action="""store_true""", help="""Whether to use 16-bit (mixed) precision instead of 32-bit""", ) parser.add_argument( """--int8""", action="""store_true""", help="""Whether to use INT8""", ) a =parser.parse_args() if args.tokenizer_name: a =AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) logger.info("""Training/evaluation parameters %s""", args) a =args.per_device_eval_batch_size a =(args.eval_batch_size, args.max_seq_length) # TRT Engine properties a =True a ="""temp_engine/bert-fp32.engine""" if args.fpaa: a ="""temp_engine/bert-fp16.engine""" if args.inta: a ="""temp_engine/bert-int8.engine""" # import ONNX file if not os.path.exists("""temp_engine"""): os.makedirs("""temp_engine""") a =1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, """rb""") as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network a =[network.get_input(i) for i in range(network.num_inputs)] a =[_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: a =1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) a =builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) a =builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, """wb""") as f: f.write(engine.serialize()) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : List[str] = np.asarray(inputs['input_ids'] , dtype=np.intaa ) __lowerCamelCase : Dict = np.asarray(inputs['attention_mask'] , dtype=np.intaa ) __lowerCamelCase : Dict = np.asarray(inputs['token_type_ids'] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowerCamelCase__ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowerCamelCase__ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowerCamelCase__ ) # start time __lowerCamelCase : Optional[Any] = time.time() # Run inference context.execute_async( bindings=[int(lowerCamelCase__ ) for d_inp in d_inputs] + [int(lowerCamelCase__ ), int(lowerCamelCase__ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) cuda.memcpy_dtoh_async(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Synchronize the stream and take time stream.synchronize() # end time __lowerCamelCase : List[str] = time.time() __lowerCamelCase : List[Any] = end_time - start_time __lowerCamelCase : Tuple = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. a =Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. a =load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError("""Evaluation requires a dataset name""") # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. a =raw_datasets["""validation"""].column_names a ="""question""" if """question""" in column_names else column_names[0] a ="""context""" if """context""" in column_names else column_names[1] a ="""answers""" if """answers""" in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). a =tokenizer.padding_side == """right""" if args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) a =min(args.max_seq_length, tokenizer.model_max_length) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace __lowerCamelCase : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __lowerCamelCase : Optional[int] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='only_second' if pad_on_right else 'only_first' , max_length=lowerCamelCase__ , stride=args.doc_stride , return_overflowing_tokens=lowerCamelCase__ , return_offsets_mapping=lowerCamelCase__ , padding='max_length' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __lowerCamelCase : Union[str, Any] = tokenized_examples.pop('overflow_to_sample_mapping' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __lowerCamelCase : int = [] for i in range(len(tokenized_examples['input_ids'] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __lowerCamelCase : List[str] = tokenized_examples.sequence_ids(lowerCamelCase__ ) __lowerCamelCase : Optional[int] = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __lowerCamelCase : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['id'][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __lowerCamelCase : Dict = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['offset_mapping'][i] ) ] return tokenized_examples a =raw_datasets["""validation"""] # Validation Feature Creation a =eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc="""Running tokenizer on validation dataset""", ) a =default_data_collator a =eval_dataset.remove_columns(["""example_id""", """offset_mapping"""]) a =DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="eval" ) -> Any: # Post-processing: we match the start logits and end logits to answers in the original context. __lowerCamelCase : Optional[int] = postprocess_qa_predictions( examples=lowerCamelCase__ , features=lowerCamelCase__ , predictions=lowerCamelCase__ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowerCamelCase__ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __lowerCamelCase : List[str] = [ {'id': k, 'prediction_text': v, 'no_answer_probability': 0.0} for k, v in predictions.items() ] else: __lowerCamelCase : Any = [{'id': k, 'prediction_text': v} for k, v in predictions.items()] __lowerCamelCase : List[str] = [{'id': ex['id'], 'answers': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowerCamelCase__ , label_ids=lowerCamelCase__ ) a =load_metric("""squad_v2""" if args.version_2_with_negative else """squad""") # Evaluation! logger.info("""Loading ONNX model %s for evaluation""", args.onnx_model_path) with open(engine_name, """rb""") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: return trt.volume(engine.get_binding_shape(lowerCamelCase__ ) ) * engine.get_binding_dtype(lowerCamelCase__ ).itemsize # Allocate device memory for inputs and outputs. a =[cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer a =cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) a =cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) a =cuda.mem_alloc(h_outputa.nbytes) a =cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. a =cuda.Stream() # Evaluation logger.info("""***** Running Evaluation *****""") logger.info(F""" Num examples = {len(eval_dataset)}""") logger.info(F""" Batch size = {args.per_device_eval_batch_size}""") a =0.0 a =0 a =timeit.default_timer() a =None for step, batch in enumerate(eval_dataloader): a , a =model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 a , a =outputs a =torch.tensor(start_logits) a =torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered a =accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100) a =accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100) a =(accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) a =logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if all_preds is not None: a =nested_truncate(all_preds, len(eval_dataset)) a =timeit.default_timer() - start_time logger.info(""" Evaluation done in total %f secs (%f sec per example)""", evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info("""Average Inference Time = {:.3f} ms""".format(total_time * 1000 / niter)) logger.info("""Total Inference Time = {:.3f} ms""".format(total_time * 1000)) logger.info("""Total Number of Inference = %d""", niter) a =post_processing_function(eval_examples, eval_dataset, all_preds) a =metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(F"""Evaluation metrics: {eval_metric}""")
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
1
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : int = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: __lowerCamelCase , __lowerCamelCase : List[Any] = emb.weight.shape __lowerCamelCase : Tuple = nn.Linear(lowerCamelCase__ , lowerCamelCase__ , bias=lowerCamelCase__ ) __lowerCamelCase : Optional[int] = emb.weight.data return lin_layer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : Optional[Any] = torch.load(lowerCamelCase__ , map_location='cpu' ) __lowerCamelCase : List[str] = mam_aaa['args'] or mam_aaa['cfg']['model'] __lowerCamelCase : Tuple = mam_aaa['model'] remove_ignore_keys_(lowerCamelCase__ ) __lowerCamelCase : Any = state_dict['encoder.embed_tokens.weight'].shape[0] __lowerCamelCase : List[Any] = MaMaaaConfig( vocab_size=lowerCamelCase__ , max_position_embeddings=1_0_2_4 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) __lowerCamelCase : Any = state_dict['decoder.embed_tokens.weight'] __lowerCamelCase : Any = MaMaaaForConditionalGeneration(lowerCamelCase__ ) model.model.load_state_dict(lowerCamelCase__ , strict=lowerCamelCase__ ) __lowerCamelCase : List[Any] = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": a =argparse.ArgumentParser() # Required parameters parser.add_argument("""fairseq_path""", type=str, help="""path to a model.pt on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") a =parser.parse_args() a =convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
73
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
1
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor _UpperCAmelCase : Optional[torch.FloatTensor] = None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=0.999 , lowerCamelCase__="cosine" , ) -> Dict: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCamelCase__ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCamelCase__ ): return math.exp(t * -12.0 ) else: raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}" ) __lowerCamelCase : List[Any] = [] for i in range(lowerCamelCase__ ): __lowerCamelCase : str = i / num_diffusion_timesteps __lowerCamelCase : Optional[int] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCamelCase__ ) / alpha_bar_fn(lowerCamelCase__ ) , lowerCamelCase__ ) ) return torch.tensor(lowerCamelCase__ , dtype=torch.floataa ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): @register_to_config def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : int = 1_0_0_0 ,SCREAMING_SNAKE_CASE__ : str = "fixed_small_log" ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[float] = 1.0 ,SCREAMING_SNAKE_CASE__ : str = "epsilon" ,SCREAMING_SNAKE_CASE__ : str = "squaredcos_cap_v2" ,): if beta_schedule != "squaredcos_cap_v2": raise ValueError('UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'') __lowerCamelCase : Tuple = betas_for_alpha_bar(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = 1.0 - self.betas __lowerCamelCase : List[str] = torch.cumprod(self.alphas ,dim=0) __lowerCamelCase : str = torch.tensor(1.0) # standard deviation of the initial noise distribution __lowerCamelCase : Tuple = 1.0 # setable values __lowerCamelCase : Optional[int] = None __lowerCamelCase : List[Any] = torch.from_numpy(np.arange(0 ,SCREAMING_SNAKE_CASE__)[::-1].copy()) __lowerCamelCase : Optional[int] = variance_type def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None): return sample def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Union[str, torch.device] = None): __lowerCamelCase : List[str] = num_inference_steps __lowerCamelCase : List[str] = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) __lowerCamelCase : int = (np.arange(0 ,SCREAMING_SNAKE_CASE__) * step_ratio).round()[::-1].copy().astype(np.intaa) __lowerCamelCase : List[str] = torch.from_numpy(SCREAMING_SNAKE_CASE__).to(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,SCREAMING_SNAKE_CASE__ : Any=None): if prev_timestep is None: __lowerCamelCase : Any = t - 1 __lowerCamelCase : List[str] = self.alphas_cumprod[t] __lowerCamelCase : Union[str, Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __lowerCamelCase : Optional[int] = 1 - alpha_prod_t __lowerCamelCase : Dict = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __lowerCamelCase : Any = self.betas[t] else: __lowerCamelCase : Dict = 1 - alpha_prod_t / alpha_prod_t_prev # 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 : Union[str, Any] = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: __lowerCamelCase : Tuple = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": __lowerCamelCase : Optional[int] = torch.log(torch.clamp(SCREAMING_SNAKE_CASE__ ,min=1E-20)) __lowerCamelCase : Dict = torch.exp(0.5 * variance) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler __lowerCamelCase : List[Any] = variance.log() __lowerCamelCase : List[str] = beta.log() __lowerCamelCase : str = (predicted_variance + 1) / 2 __lowerCamelCase : Tuple = frac * max_log + (1 - frac) * min_log return variance def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : Union[str, Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.split(SCREAMING_SNAKE_CASE__ ,sample.shape[1] ,dim=1) else: __lowerCamelCase : str = None # 1. compute alphas, betas if prev_timestep is None: __lowerCamelCase : int = t - 1 __lowerCamelCase : str = self.alphas_cumprod[t] __lowerCamelCase : List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __lowerCamelCase : List[str] = 1 - alpha_prod_t __lowerCamelCase : Tuple = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __lowerCamelCase : str = self.betas[t] __lowerCamelCase : Union[str, Any] = self.alphas[t] else: __lowerCamelCase : Dict = 1 - alpha_prod_t / alpha_prod_t_prev __lowerCamelCase : Optional[Any] = 1 - beta # 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 : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": __lowerCamelCase : Tuple = model_output else: raise ValueError( F"prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`" ' for the UnCLIPScheduler.') # 3. Clip "predicted x_0" if self.config.clip_sample: __lowerCamelCase : Tuple = torch.clamp( SCREAMING_SNAKE_CASE__ ,-self.config.clip_sample_range ,self.config.clip_sample_range) # 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 : Optional[int] = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t __lowerCamelCase : List[Any] = alpha ** 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 __lowerCamelCase : Tuple = 0 if t > 0: __lowerCamelCase : List[str] = randn_tensor( model_output.shape ,dtype=model_output.dtype ,generator=SCREAMING_SNAKE_CASE__ ,device=model_output.device) __lowerCamelCase : Dict = self._get_variance( SCREAMING_SNAKE_CASE__ ,predicted_variance=SCREAMING_SNAKE_CASE__ ,prev_timestep=SCREAMING_SNAKE_CASE__ ,) if self.variance_type == "fixed_small_log": __lowerCamelCase : List[Any] = variance elif self.variance_type == "learned_range": __lowerCamelCase : Optional[int] = (0.5 * variance).exp() else: raise ValueError( F"variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`" ' for the UnCLIPScheduler.') __lowerCamelCase : Union[str, Any] = variance * variance_noise __lowerCamelCase : Dict = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__ ,pred_original_sample=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : torch.IntTensor ,): # Make sure alphas_cumprod and timestep have same device and dtype as original_samples __lowerCamelCase : List[Any] = self.alphas_cumprod.to(device=original_samples.device ,dtype=original_samples.dtype) __lowerCamelCase : Optional[int] = timesteps.to(original_samples.device) __lowerCamelCase : Tuple = alphas_cumprod[timesteps] ** 0.5 __lowerCamelCase : Dict = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape) < len(original_samples.shape): __lowerCamelCase : int = sqrt_alpha_prod.unsqueeze(-1) __lowerCamelCase : Any = (1 - alphas_cumprod[timesteps]) ** 0.5 __lowerCamelCase : Dict = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape): __lowerCamelCase : Optional[int] = sqrt_one_minus_alpha_prod.unsqueeze(-1) __lowerCamelCase : Optional[int] = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
73
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
1
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets a ="""\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } """ a ="""\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. """ a =r""" Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {'accuracy': 1.0} """ @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : List[Any]): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string'), 'references': datasets.Value('string'), }) ,homepage='https://github.com/hendrycks/math' ,codebase_urls=['https://github.com/hendrycks/math'] ,) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple): __lowerCamelCase : str = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else 0.0 __lowerCamelCase : Tuple = n_correct / len(SCREAMING_SNAKE_CASE__) return { "accuracy": accuracy, }
73
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
1
import logging from transformers import PretrainedConfig a =logging.getLogger(__name__) a ={ """bertabs-finetuned-cnndm""": """https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json""", } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = '''bertabs''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_0_5_2_2 ,SCREAMING_SNAKE_CASE__ : int=5_1_2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=6 ,SCREAMING_SNAKE_CASE__ : str=5_1_2 ,SCREAMING_SNAKE_CASE__ : str=8 ,SCREAMING_SNAKE_CASE__ : int=5_1_2 ,SCREAMING_SNAKE_CASE__ : Any=0.2 ,SCREAMING_SNAKE_CASE__ : str=6 ,SCREAMING_SNAKE_CASE__ : Dict=7_6_8 ,SCREAMING_SNAKE_CASE__ : int=8 ,SCREAMING_SNAKE_CASE__ : Dict=2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int=0.2 ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = vocab_size __lowerCamelCase : Optional[Any] = max_pos __lowerCamelCase : List[Any] = enc_layers __lowerCamelCase : int = enc_hidden_size __lowerCamelCase : Tuple = enc_heads __lowerCamelCase : Union[str, Any] = enc_ff_size __lowerCamelCase : Union[str, Any] = enc_dropout __lowerCamelCase : Dict = dec_layers __lowerCamelCase : Union[str, Any] = dec_hidden_size __lowerCamelCase : Optional[Any] = dec_heads __lowerCamelCase : List[Any] = dec_ff_size __lowerCamelCase : Dict = dec_dropout
73
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
1
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset a ="""bert-base-cased""" a ="""google/pegasus-xsum""" a =[""" Sam ate lunch today.""", """Sams lunch ingredients."""] a =["""A very interesting story about what I ate for lunch.""", """Avocado, celery, turkey, coffee"""] a ="""patrickvonplaten/t5-tiny-random""" a ="""sshleifer/bart-tiny-random""" a ="""sshleifer/tiny-mbart""" a ="""sshleifer/tiny-marian-en-de""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : str = '\n'.join(lowerCamelCase__ ) Path(lowerCamelCase__ ).open('w' ).writelines(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Union[str, Any]: for split in ["train", "val", "test"]: _dump_articles(os.path.join(lowerCamelCase__ , F"{split}.source" ) , lowerCamelCase__ ) _dump_articles(os.path.join(lowerCamelCase__ , F"{split}.target" ) , lowerCamelCase__ ) return tmp_dir class A_ ( SCREAMING_SNAKE_CASE ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] ,) @slow def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Tuple): __lowerCamelCase : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) __lowerCamelCase : Union[str, Any] = max(len(tokenizer.encode(SCREAMING_SNAKE_CASE__)) for a in ARTICLES) __lowerCamelCase : List[str] = max(len(tokenizer.encode(SCREAMING_SNAKE_CASE__)) for a in SUMMARIES) __lowerCamelCase : str = 4 __lowerCamelCase : List[str] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated __lowerCamelCase , __lowerCamelCase : Dict = 'ro_RO', 'de_DE' # ignored for all but mbart, but never causes error. __lowerCamelCase : Dict = SeqaSeqDataset( SCREAMING_SNAKE_CASE__ ,data_dir=SCREAMING_SNAKE_CASE__ ,type_path='train' ,max_source_length=SCREAMING_SNAKE_CASE__ ,max_target_length=SCREAMING_SNAKE_CASE__ ,src_lang=SCREAMING_SNAKE_CASE__ ,tgt_lang=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = DataLoader(SCREAMING_SNAKE_CASE__ ,batch_size=2 ,collate_fn=train_dataset.collate_fn) for batch in dataloader: assert isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place __lowerCamelCase : Union[str, Any] = shift_tokens_right(batch['labels'] ,tokenizer.pad_token_id) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED]) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) __lowerCamelCase : List[Any] = max(len(tokenizer.encode(SCREAMING_SNAKE_CASE__)) for a in ARTICLES) __lowerCamelCase : List[Any] = max(len(tokenizer.encode(SCREAMING_SNAKE_CASE__)) for a in SUMMARIES) __lowerCamelCase : Dict = 4 __lowerCamelCase : List[Any] = LegacySeqaSeqDataset( SCREAMING_SNAKE_CASE__ ,data_dir=SCREAMING_SNAKE_CASE__ ,type_path='train' ,max_source_length=2_0 ,max_target_length=SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Optional[Any] = DataLoader(SCREAMING_SNAKE_CASE__ ,batch_size=2 ,collate_fn=train_dataset.collate_fn) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def lowerCAmelCase ( self : List[str]): __lowerCamelCase : int = AutoTokenizer.from_pretrained('facebook/mbart-large-cc25') __lowerCamelCase : int = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())) __lowerCamelCase : Union[str, Any] = tmp_dir.joinpath('train.source').open().readlines() __lowerCamelCase : str = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())) pack_data_dir(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,1_2_8 ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = {x.name for x in tmp_dir.iterdir()} __lowerCamelCase : Optional[int] = {x.name for x in save_dir.iterdir()} __lowerCamelCase : int = save_dir.joinpath('train.source').open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(SCREAMING_SNAKE_CASE__) < len(SCREAMING_SNAKE_CASE__) assert len(SCREAMING_SNAKE_CASE__) == 1 assert len(packed_examples[0]) == sum(len(SCREAMING_SNAKE_CASE__) for x in orig_examples) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE ,reason='This test requires fairseq') def lowerCAmelCase ( self : str): if not FAIRSEQ_AVAILABLE: return __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = self._get_dataset(max_len=6_4) __lowerCamelCase : Dict = 6_4 __lowerCamelCase : str = ds.make_dynamic_sampler(SCREAMING_SNAKE_CASE__ ,required_batch_size_multiple=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = [len(SCREAMING_SNAKE_CASE__) for x in batch_sampler] assert len(set(SCREAMING_SNAKE_CASE__)) > 1 # it's not dynamic batch size if every batch is the same length assert sum(SCREAMING_SNAKE_CASE__) == len(SCREAMING_SNAKE_CASE__) # no dropped or added examples __lowerCamelCase : Union[str, Any] = DataLoader(SCREAMING_SNAKE_CASE__ ,batch_sampler=SCREAMING_SNAKE_CASE__ ,collate_fn=ds.collate_fn ,num_workers=2) __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : Tuple = [] for batch in data_loader: __lowerCamelCase : Tuple = batch['input_ids'].shape __lowerCamelCase : Dict = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple __lowerCamelCase : int = np.product(batch['input_ids'].shape) num_src_per_batch.append(SCREAMING_SNAKE_CASE__) if num_src_tokens > (max_tokens * 1.1): failures.append(SCREAMING_SNAKE_CASE__) assert num_src_per_batch[0] == max(SCREAMING_SNAKE_CASE__) if failures: raise AssertionError(F"too many tokens in {len(SCREAMING_SNAKE_CASE__)} batches") def lowerCAmelCase ( self : Any): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = self._get_dataset(max_len=5_1_2) __lowerCamelCase : Optional[int] = 2 __lowerCamelCase : Dict = ds.make_sortish_sampler(SCREAMING_SNAKE_CASE__ ,shuffle=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = DataLoader(SCREAMING_SNAKE_CASE__ ,batch_size=SCREAMING_SNAKE_CASE__ ,collate_fn=ds.collate_fn ,num_workers=2) __lowerCamelCase : Any = DataLoader(SCREAMING_SNAKE_CASE__ ,batch_size=SCREAMING_SNAKE_CASE__ ,collate_fn=ds.collate_fn ,num_workers=2 ,sampler=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = tokenizer.pad_token_id def count_pad_tokens(SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict="input_ids"): return [batch[k].eq(SCREAMING_SNAKE_CASE__).sum().item() for batch in data_loader] assert sum(count_pad_tokens(SCREAMING_SNAKE_CASE__ ,k='labels')) < sum(count_pad_tokens(SCREAMING_SNAKE_CASE__ ,k='labels')) assert sum(count_pad_tokens(SCREAMING_SNAKE_CASE__)) < sum(count_pad_tokens(SCREAMING_SNAKE_CASE__)) assert len(SCREAMING_SNAKE_CASE__) == len(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : str=1_0_0_0 ,SCREAMING_SNAKE_CASE__ : Dict=1_2_8): if os.getenv('USE_REAL_DATA' ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : int = 'examples/seq2seq/wmt_en_ro' __lowerCamelCase : str = max_len * 2 * 6_4 if not Path(SCREAMING_SNAKE_CASE__).joinpath('train.len').exists(): save_len_file(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : Dict = 'examples/seq2seq/test_data/wmt_en_ro' __lowerCamelCase : Any = max_len * 4 save_len_file(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = SeqaSeqDataset( SCREAMING_SNAKE_CASE__ ,data_dir=SCREAMING_SNAKE_CASE__ ,type_path='train' ,max_source_length=SCREAMING_SNAKE_CASE__ ,max_target_length=SCREAMING_SNAKE_CASE__ ,n_obs=SCREAMING_SNAKE_CASE__ ,) return ds, max_tokens, tokenizer def lowerCAmelCase ( self : str): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = self._get_dataset() __lowerCamelCase : List[str] = set(DistributedSortishSampler(SCREAMING_SNAKE_CASE__ ,2_5_6 ,num_replicas=2 ,rank=0 ,add_extra_examples=SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Any = set(DistributedSortishSampler(SCREAMING_SNAKE_CASE__ ,2_5_6 ,num_replicas=2 ,rank=1 ,add_extra_examples=SCREAMING_SNAKE_CASE__)) assert idsa.intersection(SCREAMING_SNAKE_CASE__) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] ,) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ,use_fast=SCREAMING_SNAKE_CASE__) if tok_name == MBART_TINY: __lowerCamelCase : List[str] = SeqaSeqDataset( SCREAMING_SNAKE_CASE__ ,data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) ,type_path='train' ,max_source_length=4 ,max_target_length=8 ,src_lang='EN' ,tgt_lang='FR' ,) __lowerCamelCase : List[Any] = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: __lowerCamelCase : Union[str, Any] = SeqaSeqDataset( SCREAMING_SNAKE_CASE__ ,data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) ,type_path='train' ,max_source_length=4 ,max_target_length=8 ,) __lowerCamelCase : Dict = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(SCREAMING_SNAKE_CASE__) == 1 if tok_name == BART_TINY else len(SCREAMING_SNAKE_CASE__) == 0
73
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): 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 ,SCREAMING_SNAKE_CASE__) * ((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(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[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 lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): 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 : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,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
73
1
class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Union[str, Any] = name __lowerCamelCase : Optional[int] = val def __str__( self : str): return F"{self.__class__.__name__}({self.name}, {self.val})" def __lt__( self : str ,SCREAMING_SNAKE_CASE__ : List[str]): return self.val < other.val class A_ : def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Optional[Any] = {} __lowerCamelCase : Union[str, Any] = {} __lowerCamelCase : Any = self.build_heap(SCREAMING_SNAKE_CASE__) def __getitem__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : str): return self.get_value(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Dict): return (idx - 1) // 2 def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): return idx * 2 + 1 def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str]): return idx * 2 + 2 def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Tuple): return self.heap_dict[key] def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tuple): __lowerCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE__) - 1 __lowerCamelCase : Any = self.get_parent_idx(SCREAMING_SNAKE_CASE__) for idx, i in enumerate(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Tuple = idx __lowerCamelCase : Optional[Any] = i.val for i in range(SCREAMING_SNAKE_CASE__ ,-1 ,-1): self.sift_down(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) return array def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Any): while True: __lowerCamelCase : str = self.get_left_child_idx(SCREAMING_SNAKE_CASE__) # noqa: E741 __lowerCamelCase : List[str] = self.get_right_child_idx(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = idx if l < len(SCREAMING_SNAKE_CASE__) and array[l] < array[idx]: __lowerCamelCase : Optional[Any] = l if r < len(SCREAMING_SNAKE_CASE__) and array[r] < array[smallest]: __lowerCamelCase : List[str] = r if smallest != idx: __lowerCamelCase , __lowerCamelCase : Union[str, Any] = array[smallest], array[idx] ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : int = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) __lowerCamelCase : Optional[int] = smallest else: break def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Optional[Any] = self.get_parent_idx(SCREAMING_SNAKE_CASE__) while p >= 0 and self.heap[p] > self.heap[idx]: __lowerCamelCase , __lowerCamelCase : int = self.heap[idx], self.heap[p] __lowerCamelCase , __lowerCamelCase : Union[str, Any] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) __lowerCamelCase : str = p __lowerCamelCase : int = self.get_parent_idx(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): return self.heap[0] def lowerCAmelCase ( self : int): __lowerCamelCase , __lowerCamelCase : Tuple = self.heap[-1], self.heap[0] __lowerCamelCase , __lowerCamelCase : Tuple = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) __lowerCamelCase : Optional[Any] = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 ,self.heap) return x def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): self.heap.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = len(self.heap) - 1 __lowerCamelCase : str = node.val self.sift_up(len(self.heap) - 1) def lowerCAmelCase ( self : Optional[int]): return len(self.heap) == 0 def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[Any]): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" __lowerCamelCase : List[str] = new_value __lowerCamelCase : Dict = new_value self.sift_up(self.idx_of_element[node]) a =Node("""R""", -1) a =Node("""B""", 6) a =Node("""A""", 3) a =Node("""X""", 1) a =Node("""E""", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array a =MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("""Min Heap - before decrease key""") for i in my_min_heap.heap: print(i) print("""Min Heap - After decrease key of node [B -> -17]""") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
73
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
1
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class A_ : def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict): raise NotImplementedError() def lowerCAmelCase ( self : Optional[Any]): raise NotImplementedError() class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : "AutoTokenizer" ,SCREAMING_SNAKE_CASE__ : bool = False ,**SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : Tuple = tokenizer __lowerCamelCase : str = skip_prompt __lowerCamelCase : int = decode_kwargs # variables used in the streaming process __lowerCamelCase : List[str] = [] __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : int = True def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple): if len(value.shape) > 1 and value.shape[0] > 1: raise ValueError('TextStreamer only supports batch size 1') elif len(value.shape) > 1: __lowerCamelCase : int = value[0] if self.skip_prompt and self.next_tokens_are_prompt: __lowerCamelCase : Optional[Any] = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist()) __lowerCamelCase : List[Any] = self.tokenizer.decode(self.token_cache ,**self.decode_kwargs) # After the symbol for a new line, we flush the cache. if text.endswith('\n'): __lowerCamelCase : Optional[int] = text[self.print_len :] __lowerCamelCase : Any = [] __lowerCamelCase : Optional[Any] = 0 # If the last token is a CJK character, we print the characters. elif len(SCREAMING_SNAKE_CASE__) > 0 and self._is_chinese_char(ord(text[-1])): __lowerCamelCase : int = text[self.print_len :] self.print_len += len(SCREAMING_SNAKE_CASE__) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: __lowerCamelCase : Tuple = text[self.print_len : text.rfind(' ') + 1] self.print_len += len(SCREAMING_SNAKE_CASE__) self.on_finalized_text(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): # Flush the cache, if it exists if len(self.token_cache) > 0: __lowerCamelCase : Dict = self.tokenizer.decode(self.token_cache ,**self.decode_kwargs) __lowerCamelCase : List[str] = text[self.print_len :] __lowerCamelCase : Dict = [] __lowerCamelCase : Dict = 0 else: __lowerCamelCase : Union[str, Any] = '' __lowerCamelCase : List[Any] = True self.on_finalized_text(SCREAMING_SNAKE_CASE__ ,stream_end=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : bool = False): print(SCREAMING_SNAKE_CASE__ ,flush=SCREAMING_SNAKE_CASE__ ,end='' if not stream_end else None) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0x4e00 and cp <= 0x9fff) or (cp >= 0x3400 and cp <= 0x4dbf) # or (cp >= 0x20000 and cp <= 0x2a6df) # or (cp >= 0x2a700 and cp <= 0x2b73f) # or (cp >= 0x2b740 and cp <= 0x2b81f) # or (cp >= 0x2b820 and cp <= 0x2ceaf) # or (cp >= 0xf900 and cp <= 0xfaff) or (cp >= 0x2f800 and cp <= 0x2fa1f) # ): # return True return False class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : "AutoTokenizer" ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[float] = None ,**SCREAMING_SNAKE_CASE__ : List[str]): super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = Queue() __lowerCamelCase : str = None __lowerCamelCase : List[str] = timeout def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : bool = False): self.text_queue.put(SCREAMING_SNAKE_CASE__ ,timeout=self.timeout) if stream_end: self.text_queue.put(self.stop_signal ,timeout=self.timeout) def __iter__( self : int): return self def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Tuple = self.text_queue.get(timeout=self.timeout) if value == self.stop_signal: raise StopIteration() else: return value
73
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
1
import string from math import logaa def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Tuple = document.translate( str.maketrans('' , '' , string.punctuation ) ).replace('\n' , '' ) __lowerCamelCase : int = document_without_punctuation.split(' ' ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> tuple[int, int]: __lowerCamelCase : List[Any] = corpus.lower().translate( str.maketrans('' , '' , string.punctuation ) ) # strip all punctuation and replace it with '' __lowerCamelCase : Union[str, Any] = corpus_without_punctuation.split('\n' ) __lowerCamelCase : Optional[int] = term.lower() return (len([doc for doc in docs if term in doc] ), len(lowerCamelCase__ )) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ) -> float: if smoothing: if n == 0: raise ValueError('log10(0) is undefined.' ) return round(1 + logaa(n / (1 + df) ) , 3 ) if df == 0: raise ZeroDivisionError('df must be > 0' ) elif n == 0: raise ValueError('log10(0) is undefined.' ) return round(logaa(n / df ) , 3 ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: return round(tf * idf , 3 )
73
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a ={ """configuration_longformer""": [ """LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongformerConfig""", """LongformerOnnxConfig""", ], """tokenization_longformer""": ["""LongformerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""LongformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """LongformerForMaskedLM""", """LongformerForMultipleChoice""", """LongformerForQuestionAnswering""", """LongformerForSequenceClassification""", """LongformerForTokenClassification""", """LongformerModel""", """LongformerPreTrainedModel""", """LongformerSelfAttention""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLongformerForMaskedLM""", """TFLongformerForMultipleChoice""", """TFLongformerForQuestionAnswering""", """TFLongformerForSequenceClassification""", """TFLongformerForTokenClassification""", """TFLongformerModel""", """TFLongformerPreTrainedModel""", """TFLongformerSelfAttention""", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''gpt_neox_japanese''' def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple=3_2_0_0_0 ,SCREAMING_SNAKE_CASE__ : str=2_5_6_0 ,SCREAMING_SNAKE_CASE__ : str=3_2 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=4 ,SCREAMING_SNAKE_CASE__ : int="gelu" ,SCREAMING_SNAKE_CASE__ : Optional[int]=1.00 ,SCREAMING_SNAKE_CASE__ : Any=1_0_0_0_0 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=2_0_4_8 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=1E-5 ,SCREAMING_SNAKE_CASE__ : Optional[int]=True ,SCREAMING_SNAKE_CASE__ : int=3_1_9_9_6 ,SCREAMING_SNAKE_CASE__ : Dict=3_1_9_9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Dict=0.0 ,**SCREAMING_SNAKE_CASE__ : int ,): super().__init__(bos_token_id=SCREAMING_SNAKE_CASE__ ,eos_token_id=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : str = intermediate_multiple_size __lowerCamelCase : str = hidden_act __lowerCamelCase : Any = rotary_pct __lowerCamelCase : Union[str, Any] = rotary_emb_base __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : str = layer_norm_eps __lowerCamelCase : Optional[Any] = use_cache __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : str = hidden_dropout
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) a ={} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
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 A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = '''realm''' def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str=3_0_5_2_2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 ,SCREAMING_SNAKE_CASE__ : int=1_2_8 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 ,SCREAMING_SNAKE_CASE__ : List[str]=1_2 ,SCREAMING_SNAKE_CASE__ : Any=8 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_0_7_2 ,SCREAMING_SNAKE_CASE__ : int="gelu_new" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1 ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=2 ,SCREAMING_SNAKE_CASE__ : int=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-12 ,SCREAMING_SNAKE_CASE__ : Dict=2_5_6 ,SCREAMING_SNAKE_CASE__ : str=1_0 ,SCREAMING_SNAKE_CASE__ : Any=1E-3 ,SCREAMING_SNAKE_CASE__ : List[str]=5 ,SCREAMING_SNAKE_CASE__ : str=3_2_0 ,SCREAMING_SNAKE_CASE__ : int=1_3_3_5_3_7_1_8 ,SCREAMING_SNAKE_CASE__ : Dict=5_0_0_0 ,SCREAMING_SNAKE_CASE__ : int=1 ,SCREAMING_SNAKE_CASE__ : List[Any]=0 ,SCREAMING_SNAKE_CASE__ : Optional[int]=2 ,**SCREAMING_SNAKE_CASE__ : Union[str, Any] ,): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ ,bos_token_id=SCREAMING_SNAKE_CASE__ ,eos_token_id=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) # Common config __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : str = max_position_embeddings __lowerCamelCase : str = hidden_size __lowerCamelCase : List[str] = retriever_proj_size __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : str = num_attention_heads __lowerCamelCase : List[Any] = num_candidates __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : Optional[Any] = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : str = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = initializer_range __lowerCamelCase : Dict = type_vocab_size __lowerCamelCase : List[str] = layer_norm_eps # Reader config __lowerCamelCase : Dict = span_hidden_size __lowerCamelCase : List[Any] = max_span_width __lowerCamelCase : Dict = reader_layer_norm_eps __lowerCamelCase : List[str] = reader_beam_size __lowerCamelCase : Optional[Any] = reader_seq_len # Retrieval config __lowerCamelCase : Optional[Any] = num_block_records __lowerCamelCase : Optional[Any] = searcher_beam_size
73
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
import itertools import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def SCREAMING_SNAKE_CASE__ ( ) -> str: __lowerCamelCase : List[str] = 2 while True: if is_prime(lowerCamelCase__ ): yield num num += 1 def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1_0_0_0_1 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , lowerCamelCase__ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
73
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
1
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
1
import logging from transformers.configuration_utils import PretrainedConfig a =logging.getLogger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = '''masked_bert''' def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]=3_0_5_2_2 ,SCREAMING_SNAKE_CASE__ : str=7_6_8 ,SCREAMING_SNAKE_CASE__ : List[str]=1_2 ,SCREAMING_SNAKE_CASE__ : List[str]=1_2 ,SCREAMING_SNAKE_CASE__ : str=3_0_7_2 ,SCREAMING_SNAKE_CASE__ : Tuple="gelu" ,SCREAMING_SNAKE_CASE__ : Tuple=0.1 ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : Any=5_1_2 ,SCREAMING_SNAKE_CASE__ : List[str]=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Any=1E-12 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0 ,SCREAMING_SNAKE_CASE__ : Optional[int]="topK" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="constant" ,SCREAMING_SNAKE_CASE__ : str=0.0 ,**SCREAMING_SNAKE_CASE__ : Tuple ,): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Optional[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Optional[Any] = intermediate_size __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : List[Any] = type_vocab_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : str = layer_norm_eps __lowerCamelCase : int = pruning_method __lowerCamelCase : str = mask_init __lowerCamelCase : Union[str, Any] = mask_scale
73
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[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 lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
1
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : str=1_0_2_4 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_0_2_4 ,SCREAMING_SNAKE_CASE__ : Tuple=3.6): __lowerCamelCase : Dict = tokenizer __lowerCamelCase : List[str] = tokenizer.bos_token_id __lowerCamelCase : str = dataset __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : Union[str, Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self : List[str]): __lowerCamelCase : Any = iter(self.dataset) __lowerCamelCase : Dict = True while more_examples: __lowerCamelCase , __lowerCamelCase : Optional[int] = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE__)['content']) buffer_len += len(buffer[-1]) except StopIteration: __lowerCamelCase : Optional[Any] = False break __lowerCamelCase : Optional[int] = tokenizer(SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__)['input_ids'] __lowerCamelCase : Optional[int] = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id]) for i in range(0 ,len(SCREAMING_SNAKE_CASE__) ,self.seq_length): __lowerCamelCase : Tuple = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE__) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : Any = {'streaming': True} __lowerCamelCase : Any = load_dataset(args.dataset_name , split='train' , **lowerCamelCase__ ) __lowerCamelCase : List[Any] = ConstantLengthDataset(lowerCamelCase__ , lowerCamelCase__ , seq_length=args.seq_length ) __lowerCamelCase : Optional[Any] = DataLoader(lowerCamelCase__ , batch_size=args.batch_size ) return eval_dataloader def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: model.eval() __lowerCamelCase : Optional[int] = [] for step, batch in enumerate(lowerCamelCase__ ): with torch.no_grad(): __lowerCamelCase : Optional[Any] = model(lowerCamelCase__ , labels=lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(lowerCamelCase__ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __lowerCamelCase : Optional[Any] = torch.mean(torch.cat(lowerCamelCase__ ) ) try: __lowerCamelCase : Optional[int] = torch.exp(lowerCamelCase__ ) except OverflowError: __lowerCamelCase : Union[str, Any] = float('inf' ) return loss.item(), perplexity.item() # Setup Accelerator a =Accelerator() # Parse configuration a =HfArgumentParser(EvaluationArguments) a =parser.parse_args() set_seed(args.seed) # Logging a =logging.getLogger(__name__) logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) # Load model and tokenizer a =AutoModelForCausalLM.from_pretrained(args.model_ckpt) a =AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader a =create_dataloader(args) # Prepare everything with our `accelerator`. a , a =accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info("""Evaluating and saving model after training""") a , a =evaluate(args) logger.info(F"""loss/eval: {eval_loss}, perplexity: {perplexity}""")
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a ={"""configuration_opt""": ["""OPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OPTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """OPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OPTForCausalLM""", """OPTModel""", """OPTPreTrainedModel""", """OPTForSequenceClassification""", """OPTForQuestionAnswering""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""TFOPTForCausalLM""", """TFOPTModel""", """TFOPTPreTrainedModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """FlaxOPTForCausalLM""", """FlaxOPTModel""", """FlaxOPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = CycleDiffusionPipeline _UpperCAmelCase : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } _UpperCAmelCase : int = PipelineTesterMixin.required_optional_params - {'''latents'''} _UpperCAmelCase : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} ) _UpperCAmelCase : Union[str, Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS _UpperCAmelCase : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase ( self : Optional[int]): torch.manual_seed(0) __lowerCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(3_2, 6_4) ,layers_per_block=2 ,sample_size=3_2 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=3_2 ,) __lowerCamelCase : Optional[int] = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,num_train_timesteps=1_0_0_0 ,clip_sample=SCREAMING_SNAKE_CASE__ ,set_alpha_to_one=SCREAMING_SNAKE_CASE__ ,) torch.manual_seed(0) __lowerCamelCase : str = AutoencoderKL( 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 ,) torch.manual_seed(0) __lowerCamelCase : List[Any] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=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 ,) __lowerCamelCase : int = CLIPTextModel(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') __lowerCamelCase : Tuple = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[str]=0): __lowerCamelCase : str = floats_tensor((1, 3, 3_2, 3_2) ,rng=random.Random(SCREAMING_SNAKE_CASE__)).to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = image / 2 + 0.5 if str(SCREAMING_SNAKE_CASE__).startswith('mps'): __lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : Tuple = torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = { 'prompt': 'An astronaut riding an elephant', 'source_prompt': 'An astronaut riding a horse', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'eta': 0.1, 'strength': 0.8, 'guidance_scale': 3, 'source_guidance_scale': 1, 'output_type': 'numpy', } return inputs def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : Dict = CycleDiffusionPipeline(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = pipe(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = output.images __lowerCamelCase : Tuple = images[0, -3:, -3:, -1] assert images.shape == (1, 3_2, 3_2, 3) __lowerCamelCase : Optional[int] = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 @unittest.skipIf(torch_device != 'cuda' ,'This test requires a GPU') def lowerCAmelCase ( self : str): __lowerCamelCase : Any = self.get_dummy_components() for name, module in components.items(): if hasattr(SCREAMING_SNAKE_CASE__ ,'half'): __lowerCamelCase : Any = module.half() __lowerCamelCase : Union[str, Any] = CycleDiffusionPipeline(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = pipe(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = output.images __lowerCamelCase : Any = images[0, -3:, -3:, -1] assert images.shape == (1, 3_2, 3_2, 3) __lowerCamelCase : Optional[int] = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 @skip_mps def lowerCAmelCase ( self : Dict): return super().test_save_load_local() @unittest.skip('non-deterministic pipeline') def lowerCAmelCase ( self : Optional[Any]): return super().test_inference_batch_single_identical() @skip_mps def lowerCAmelCase ( self : Any): return super().test_dict_tuple_outputs_equivalent() @skip_mps def lowerCAmelCase ( self : Optional[Any]): return super().test_save_load_optional_components() @skip_mps def lowerCAmelCase ( self : Tuple): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[Any]): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Tuple = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/cycle-diffusion/black_colored_car.png') __lowerCamelCase : Tuple = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy') __lowerCamelCase : Optional[int] = init_image.resize((5_1_2, 5_1_2)) __lowerCamelCase : Optional[int] = 'CompVis/stable-diffusion-v1-4' __lowerCamelCase : Tuple = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ,subfolder='scheduler') __lowerCamelCase : Optional[int] = CycleDiffusionPipeline.from_pretrained( SCREAMING_SNAKE_CASE__ ,scheduler=SCREAMING_SNAKE_CASE__ ,safety_checker=SCREAMING_SNAKE_CASE__ ,torch_dtype=torch.floataa ,revision='fp16') pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) pipe.enable_attention_slicing() __lowerCamelCase : Union[str, Any] = 'A black colored car' __lowerCamelCase : Optional[int] = 'A blue colored car' __lowerCamelCase : List[Any] = torch.manual_seed(0) __lowerCamelCase : Union[str, Any] = pipe( prompt=SCREAMING_SNAKE_CASE__ ,source_prompt=SCREAMING_SNAKE_CASE__ ,image=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,eta=0.1 ,strength=0.85 ,guidance_scale=3 ,source_guidance_scale=1 ,generator=SCREAMING_SNAKE_CASE__ ,output_type='np' ,) __lowerCamelCase : List[Any] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image).max() < 5E-1 def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/cycle-diffusion/black_colored_car.png') __lowerCamelCase : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy') __lowerCamelCase : List[str] = init_image.resize((5_1_2, 5_1_2)) __lowerCamelCase : int = 'CompVis/stable-diffusion-v1-4' __lowerCamelCase : int = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ,subfolder='scheduler') __lowerCamelCase : Optional[Any] = CycleDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ ,scheduler=SCREAMING_SNAKE_CASE__ ,safety_checker=SCREAMING_SNAKE_CASE__) pipe.to(SCREAMING_SNAKE_CASE__) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) pipe.enable_attention_slicing() __lowerCamelCase : str = 'A black colored car' __lowerCamelCase : List[str] = 'A blue colored car' __lowerCamelCase : int = torch.manual_seed(0) __lowerCamelCase : Tuple = pipe( prompt=SCREAMING_SNAKE_CASE__ ,source_prompt=SCREAMING_SNAKE_CASE__ ,image=SCREAMING_SNAKE_CASE__ ,num_inference_steps=1_0_0 ,eta=0.1 ,strength=0.85 ,guidance_scale=3 ,source_guidance_scale=1 ,generator=SCREAMING_SNAKE_CASE__ ,output_type='np' ,) __lowerCamelCase : List[Any] = output.images assert np.abs(image - expected_image).max() < 2E-2
73
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
1
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: __lowerCamelCase : List[Any] = len(lowerCamelCase__ ) while cur > 1: # Find the maximum number in arr __lowerCamelCase : List[Any] = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi __lowerCamelCase : Any = arr[mi::-1] + arr[mi + 1 : len(lowerCamelCase__ )] # Reverse whole list __lowerCamelCase : str = arr[cur - 1 :: -1] + arr[cur : len(lowerCamelCase__ )] cur -= 1 return arr if __name__ == "__main__": a =input("""Enter numbers separated by a comma:\n""").strip() a =[int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
73
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
1
from collections import namedtuple a =namedtuple("""from_to""", """from_ to""") a ={ """cubicmeter""": from_to(1, 1), """litre""": from_to(0.0_01, 1000), """kilolitre""": from_to(1, 1), """gallon""": from_to(0.0_04_54, 2_64.1_72), """cubicyard""": from_to(0.7_64_55, 1.3_07_95), """cubicfoot""": from_to(0.0_28, 35.31_47), """cup""": from_to(0.0_00_23_65_88, 42_26.75), } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ', '.join(lowerCamelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ', '.join(lowerCamelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): @register_to_config def __init__( self : int ,SCREAMING_SNAKE_CASE__ : int = 1_2_8 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : float = 2000.0 ,SCREAMING_SNAKE_CASE__ : int = 7_6_8 ,SCREAMING_SNAKE_CASE__ : int = 1_2 ,SCREAMING_SNAKE_CASE__ : int = 1_2 ,SCREAMING_SNAKE_CASE__ : int = 6_4 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,): super().__init__() __lowerCamelCase : Optional[Any] = nn.Sequential( nn.Linear(SCREAMING_SNAKE_CASE__ ,d_model * 4 ,bias=SCREAMING_SNAKE_CASE__) ,nn.SiLU() ,nn.Linear(d_model * 4 ,d_model * 4 ,bias=SCREAMING_SNAKE_CASE__) ,nn.SiLU() ,) __lowerCamelCase : Tuple = nn.Embedding(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = False __lowerCamelCase : Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = nn.Dropout(p=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = nn.ModuleList() for lyr_num in range(SCREAMING_SNAKE_CASE__): # FiLM conditional T5 decoder __lowerCamelCase : Optional[int] = DecoderLayer(d_model=SCREAMING_SNAKE_CASE__ ,d_kv=SCREAMING_SNAKE_CASE__ ,num_heads=SCREAMING_SNAKE_CASE__ ,d_ff=SCREAMING_SNAKE_CASE__ ,dropout_rate=SCREAMING_SNAKE_CASE__) self.decoders.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = TaLayerNorm(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = nn.Dropout(p=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : Tuple = torch.mul(query_input.unsqueeze(-1) ,key_input.unsqueeze(-2)) return mask.unsqueeze(-3) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. __lowerCamelCase : Dict = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time ,embedding_dim=self.config.d_model ,max_period=self.config.max_decoder_noise_time ,).to(dtype=self.dtype) __lowerCamelCase : List[Any] = self.conditioning_emb(SCREAMING_SNAKE_CASE__).unsqueeze(1) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) __lowerCamelCase : Any = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. __lowerCamelCase : Tuple = torch.broadcast_to( torch.arange(SCREAMING_SNAKE_CASE__ ,device=decoder_input_tokens.device) ,(batch, seq_length) ,) __lowerCamelCase : Tuple = self.position_encoding(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.continuous_inputs_projection(SCREAMING_SNAKE_CASE__) inputs += position_encodings __lowerCamelCase : str = self.dropout(SCREAMING_SNAKE_CASE__) # decoder: No padding present. __lowerCamelCase : List[str] = torch.ones( decoder_input_tokens.shape[:2] ,device=decoder_input_tokens.device ,dtype=inputs.dtype) # Translate encoding masks to encoder-decoder masks. __lowerCamelCase : str = [(x, self.encoder_decoder_mask(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) for x, y in encodings_and_masks] # cross attend style: concat encodings __lowerCamelCase : Union[str, Any] = torch.cat([x[0] for x in encodings_and_encdec_masks] ,dim=1) __lowerCamelCase : Optional[Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] ,dim=-1) for lyr in self.decoders: __lowerCamelCase : Tuple = lyr( SCREAMING_SNAKE_CASE__ ,conditioning_emb=SCREAMING_SNAKE_CASE__ ,encoder_hidden_states=SCREAMING_SNAKE_CASE__ ,encoder_attention_mask=SCREAMING_SNAKE_CASE__ ,)[0] __lowerCamelCase : List[str] = self.decoder_norm(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.post_dropout(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.spec_out(SCREAMING_SNAKE_CASE__) return spec_out class A_ ( nn.Module ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple=1E-6): super().__init__() __lowerCamelCase : Any = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=SCREAMING_SNAKE_CASE__ ,d_kv=SCREAMING_SNAKE_CASE__ ,num_heads=SCREAMING_SNAKE_CASE__ ,dropout_rate=SCREAMING_SNAKE_CASE__)) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=SCREAMING_SNAKE_CASE__ ,d_kv=SCREAMING_SNAKE_CASE__ ,num_heads=SCREAMING_SNAKE_CASE__ ,dropout_rate=SCREAMING_SNAKE_CASE__ ,layer_norm_epsilon=SCREAMING_SNAKE_CASE__ ,)) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=SCREAMING_SNAKE_CASE__ ,d_ff=SCREAMING_SNAKE_CASE__ ,dropout_rate=SCREAMING_SNAKE_CASE__ ,layer_norm_epsilon=SCREAMING_SNAKE_CASE__)) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : str=None ,): __lowerCamelCase : Any = self.layer[0]( SCREAMING_SNAKE_CASE__ ,conditioning_emb=SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,) if encoder_hidden_states is not None: __lowerCamelCase : Tuple = torch.where(encoder_attention_mask > 0 ,0 ,-1E10).to( encoder_hidden_states.dtype) __lowerCamelCase : Any = self.layer[1]( SCREAMING_SNAKE_CASE__ ,key_value_states=SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,) # Apply Film Conditional Feed Forward layer __lowerCamelCase : Tuple = self.layer[-1](SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) return (hidden_states,) class A_ ( nn.Module ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): super().__init__() __lowerCamelCase : int = TaLayerNorm(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = TaFiLMLayer(in_features=d_model * 4 ,out_features=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = Attention(query_dim=SCREAMING_SNAKE_CASE__ ,heads=SCREAMING_SNAKE_CASE__ ,dim_head=SCREAMING_SNAKE_CASE__ ,out_bias=SCREAMING_SNAKE_CASE__ ,scale_qk=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = nn.Dropout(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ,SCREAMING_SNAKE_CASE__ : List[str]=None ,): # pre_self_attention_layer_norm __lowerCamelCase : Dict = self.layer_norm(SCREAMING_SNAKE_CASE__) if conditioning_emb is not None: __lowerCamelCase : int = self.FiLMLayer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # Self-attention block __lowerCamelCase : int = self.attention(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = hidden_states + self.dropout(SCREAMING_SNAKE_CASE__) return hidden_states class A_ ( nn.Module ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple): super().__init__() __lowerCamelCase : str = Attention(query_dim=SCREAMING_SNAKE_CASE__ ,heads=SCREAMING_SNAKE_CASE__ ,dim_head=SCREAMING_SNAKE_CASE__ ,out_bias=SCREAMING_SNAKE_CASE__ ,scale_qk=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = TaLayerNorm(SCREAMING_SNAKE_CASE__ ,eps=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = nn.Dropout(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,): __lowerCamelCase : str = self.layer_norm(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.attention( SCREAMING_SNAKE_CASE__ ,encoder_hidden_states=SCREAMING_SNAKE_CASE__ ,attention_mask=attention_mask.squeeze(1) ,) __lowerCamelCase : Optional[int] = hidden_states + self.dropout(SCREAMING_SNAKE_CASE__) return layer_output class A_ ( nn.Module ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__() __lowerCamelCase : Union[str, Any] = TaDenseGatedActDense(d_model=SCREAMING_SNAKE_CASE__ ,d_ff=SCREAMING_SNAKE_CASE__ ,dropout_rate=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = TaFiLMLayer(in_features=d_model * 4 ,out_features=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = TaLayerNorm(SCREAMING_SNAKE_CASE__ ,eps=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = nn.Dropout(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Dict=None): __lowerCamelCase : List[Any] = self.layer_norm(SCREAMING_SNAKE_CASE__) if conditioning_emb is not None: __lowerCamelCase : int = self.film(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.DenseReluDense(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = hidden_states + self.dropout(SCREAMING_SNAKE_CASE__) return hidden_states class A_ ( nn.Module ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int]): super().__init__() __lowerCamelCase : Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = nn.Dropout(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = NewGELUActivation() def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : List[Any] = self.act(self.wi_a(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Optional[int] = self.wi_a(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = hidden_gelu * hidden_linear __lowerCamelCase : Tuple = self.dropout(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.wo(SCREAMING_SNAKE_CASE__) return hidden_states class A_ ( nn.Module ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1E-6): super().__init__() __lowerCamelCase : List[Any] = nn.Parameter(torch.ones(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[Any] = eps def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : int): # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 __lowerCamelCase : List[str] = hidden_states.to(torch.floataa).pow(2).mean(-1 ,keepdim=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = hidden_states * torch.rsqrt(variance + self.variance_epsilon) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: __lowerCamelCase : int = hidden_states.to(self.weight.dtype) return self.weight * hidden_states class A_ ( nn.Module ): def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : torch.Tensor): return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(SCREAMING_SNAKE_CASE__ ,3.0)))) class A_ ( nn.Module ): def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple): super().__init__() __lowerCamelCase : List[str] = nn.Linear(SCREAMING_SNAKE_CASE__ ,out_features * 2 ,bias=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : List[Any] = self.scale_bias(SCREAMING_SNAKE_CASE__) __lowerCamelCase , __lowerCamelCase : str = torch.chunk(SCREAMING_SNAKE_CASE__ ,2 ,-1) __lowerCamelCase : Tuple = x * (1 + scale) + shift return x
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
1
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 a =data_utils.TransfoXLTokenizer a =data_utils.TransfoXLCorpus a =data_utils a =data_utils def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(lowerCamelCase__ , 'rb' ) as fp: __lowerCamelCase : int = pickle.load(lowerCamelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) __lowerCamelCase : Dict = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F"Save vocabulary to {pytorch_vocab_dump_path}" ) __lowerCamelCase : Optional[int] = corpus.vocab.__dict__ torch.save(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Dict = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F"Save dataset to {pytorch_dataset_dump_path}" ) torch.save(lowerCamelCase__ , lowerCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model __lowerCamelCase : Optional[Any] = os.path.abspath(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = os.path.abspath(lowerCamelCase__ ) print(F"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}." ) # Initialise PyTorch model if transfo_xl_config_file == "": __lowerCamelCase : int = TransfoXLConfig() else: __lowerCamelCase : Dict = TransfoXLConfig.from_json_file(lowerCamelCase__ ) print(F"Building PyTorch model from configuration: {config}" ) __lowerCamelCase : str = TransfoXLLMHeadModel(lowerCamelCase__ ) __lowerCamelCase : Dict = load_tf_weights_in_transfo_xl(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Save pytorch-model __lowerCamelCase : Tuple = os.path.join(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : str = os.path.join(lowerCamelCase__ , lowerCamelCase__ ) print(F"Save PyTorch model to {os.path.abspath(lowerCamelCase__ )}" ) torch.save(model.state_dict() , lowerCamelCase__ ) print(F"Save configuration file to {os.path.abspath(lowerCamelCase__ )}" ) with open(lowerCamelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": a =argparse.ArgumentParser() parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the folder to store the PyTorch model or dataset/vocab.""", ) parser.add_argument( """--tf_checkpoint_path""", default="""""", type=str, help="""An optional path to a TensorFlow checkpoint path to be converted.""", ) parser.add_argument( """--transfo_xl_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--transfo_xl_dataset_file""", default="""""", type=str, help="""An optional dataset file to be converted in a vocabulary.""", ) a =parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
73
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
1
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image a =["""text""", """image""", """audio"""] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : List[Any] = [] for input_type in input_types: if input_type == "text": inputs.append('Text input' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('fixtures/tests_samples/COCO' ) ) / '000000039769.png' ).resize((5_1_2, 5_1_2) ) ) elif input_type == "audio": inputs.append(torch.ones(3_0_0_0 ) ) elif isinstance(lowerCamelCase__ , lowerCamelCase__ ): inputs.append(create_inputs(lowerCamelCase__ ) ) else: raise ValueError(F"Invalid type requested: {input_type}" ) return inputs def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : List[Any] = [] for output in outputs: if isinstance(lowerCamelCase__ , (str, AgentText) ): output_types.append('text' ) elif isinstance(lowerCamelCase__ , (Image.Image, AgentImage) ): output_types.append('image' ) elif isinstance(lowerCamelCase__ , (torch.Tensor, AgentAudio) ): output_types.append('audio' ) else: raise ValueError(F"Invalid output: {output}" ) return output_types @is_tool_test class A_ : def lowerCAmelCase ( self : Union[str, Any]): self.assertTrue(hasattr(self.tool ,'inputs')) self.assertTrue(hasattr(self.tool ,'outputs')) __lowerCamelCase : Dict = self.tool.inputs for _input in inputs: if isinstance(_input ,SCREAMING_SNAKE_CASE__): for __input in _input: self.assertTrue(__input in authorized_types) else: self.assertTrue(_input in authorized_types) __lowerCamelCase : Dict = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Optional[int] = create_inputs(self.tool.inputs) __lowerCamelCase : Tuple = self.tool(*SCREAMING_SNAKE_CASE__) # There is a single output if len(self.tool.outputs) == 1: __lowerCamelCase : Optional[int] = [outputs] self.assertListEqual(output_types(SCREAMING_SNAKE_CASE__) ,self.tool.outputs) def lowerCAmelCase ( self : Union[str, Any]): self.assertTrue(hasattr(self.tool ,'description')) self.assertTrue(hasattr(self.tool ,'default_checkpoint')) self.assertTrue(self.tool.description.startswith('This is a tool that')) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = create_inputs(self.tool.inputs) __lowerCamelCase : List[str] = self.tool(*SCREAMING_SNAKE_CASE__) if not isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[str] = [outputs] self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,len(self.tool.outputs)) for output, output_type in zip(SCREAMING_SNAKE_CASE__ ,self.tool.outputs): __lowerCamelCase : List[str] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) def lowerCAmelCase ( self : Any): __lowerCamelCase : Optional[Any] = create_inputs(self.tool.inputs) __lowerCamelCase : Optional[Any] = [] for _input, input_type in zip(SCREAMING_SNAKE_CASE__ ,self.tool.inputs): if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type]) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input)) # Should not raise an error __lowerCamelCase : Tuple = self.tool(*SCREAMING_SNAKE_CASE__) if not isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : int = [outputs] self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,len(self.tool.outputs))
73
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class A_ : def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]=1_3 ,SCREAMING_SNAKE_CASE__ : Dict=1_0 ,SCREAMING_SNAKE_CASE__ : List[str]=3 ,SCREAMING_SNAKE_CASE__ : int=2 ,SCREAMING_SNAKE_CASE__ : List[Any]=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : str=5 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=3_7 ,SCREAMING_SNAKE_CASE__ : List[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : List[Any]=0.1 ,SCREAMING_SNAKE_CASE__ : Any=1_0 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=0.9 ,SCREAMING_SNAKE_CASE__ : str=None ,): __lowerCamelCase : Any = parent __lowerCamelCase : List[str] = batch_size __lowerCamelCase : List[Any] = image_size __lowerCamelCase : Union[str, Any] = num_channels __lowerCamelCase : Optional[Any] = patch_size __lowerCamelCase : int = tubelet_size __lowerCamelCase : Optional[Any] = num_frames __lowerCamelCase : List[str] = is_training __lowerCamelCase : str = use_labels __lowerCamelCase : str = hidden_size __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : int = num_attention_heads __lowerCamelCase : Tuple = intermediate_size __lowerCamelCase : int = hidden_act __lowerCamelCase : Union[str, Any] = hidden_dropout_prob __lowerCamelCase : Tuple = attention_probs_dropout_prob __lowerCamelCase : List[Any] = type_sequence_label_size __lowerCamelCase : List[Any] = initializer_range __lowerCamelCase : Tuple = mask_ratio __lowerCamelCase : List[str] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 __lowerCamelCase : Union[str, Any] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos __lowerCamelCase : Any = int(mask_ratio * self.seq_length) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Any = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]) __lowerCamelCase : Optional[int] = None if self.use_labels: __lowerCamelCase : int = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : List[Any] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Optional[int]): return VideoMAEConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,num_frames=self.num_frames ,tubelet_size=self.tubelet_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 ,is_decoder=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple): __lowerCamelCase : List[str] = VideoMAEModel(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : Optional[int] = VideoMAEForPreTraining(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch __lowerCamelCase : int = torch.ones((self.num_masks,)) __lowerCamelCase : List[str] = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0))]) __lowerCamelCase : Optional[int] = mask.expand(self.batch_size ,-1).bool() __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # model only returns predictions for masked patches __lowerCamelCase : Union[str, Any] = mask.sum().item() __lowerCamelCase : str = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_masked_patches, decoder_num_labels)) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Dict = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = config_and_inputs __lowerCamelCase : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Any = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) _UpperCAmelCase : Dict = ( {'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification} if is_torch_available() else {} ) _UpperCAmelCase : Optional[Any] = False _UpperCAmelCase : str = False _UpperCAmelCase : Optional[int] = False _UpperCAmelCase : Optional[int] = False def lowerCAmelCase ( self : Any): __lowerCamelCase : str = VideoMAEModelTester(self) __lowerCamelCase : Union[str, Any] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,has_text_modality=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int]=False): __lowerCamelCase : Union[str, Any] = copy.deepcopy(SCREAMING_SNAKE_CASE__) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch __lowerCamelCase : str = torch.ones((self.model_tester.num_masks,)) __lowerCamelCase : List[Any] = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0))]) __lowerCamelCase : int = mask.expand(self.model_tester.batch_size ,-1).bool() __lowerCamelCase : str = bool_masked_pos.to(SCREAMING_SNAKE_CASE__) if return_labels: if model_class in [ *get_values(SCREAMING_SNAKE_CASE__), ]: __lowerCamelCase : int = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=SCREAMING_SNAKE_CASE__) return inputs_dict def lowerCAmelCase ( self : Dict): self.config_tester.run_common_tests() @unittest.skip(reason='VideoMAE does not use inputs_embeds') def lowerCAmelCase ( self : Any): pass def lowerCAmelCase ( self : Dict): __lowerCamelCase , __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module)) __lowerCamelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ ,nn.Linear)) def lowerCAmelCase ( self : Any): __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(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase : str = [*signature.parameters.keys()] __lowerCamelCase : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE__) @slow def lowerCAmelCase ( self : int): for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Optional[Any] = VideoMAEModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple): if not self.has_attentions: pass else: __lowerCamelCase , __lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __lowerCamelCase : Any = True for model_class in self.all_model_classes: __lowerCamelCase : int = self.model_tester.seq_length - self.model_tester.num_masks __lowerCamelCase : int = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) __lowerCamelCase : Any = True __lowerCamelCase : str = False __lowerCamelCase : Union[str, Any] = True __lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): __lowerCamelCase : str = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] __lowerCamelCase : List[str] = True __lowerCamelCase : int = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): __lowerCamelCase : List[str] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : Any = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]) ,[self.model_tester.num_attention_heads, seq_len, seq_len] ,) __lowerCamelCase : Dict = len(SCREAMING_SNAKE_CASE__) # Check attention is always last and order is fine __lowerCamelCase : Dict = True __lowerCamelCase : List[str] = True __lowerCamelCase : Tuple = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): __lowerCamelCase : Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) self.assertEqual(out_len + 1 ,len(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[Any] = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) ,[self.model_tester.num_attention_heads, seq_len, seq_len] ,) def lowerCAmelCase ( self : str): def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): __lowerCamelCase : Union[str, Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[str] = outputs.hidden_states __lowerCamelCase : Tuple = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.model_tester.seq_length - self.model_tester.num_masks __lowerCamelCase : Optional[Any] = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:]) ,[seq_length, self.model_tester.hidden_size] ,) __lowerCamelCase , __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Optional[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCamelCase : Optional[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.') def lowerCAmelCase ( self : Tuple): pass def SCREAMING_SNAKE_CASE__ ( ) -> Dict: __lowerCamelCase : Dict = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) __lowerCamelCase : int = np.load(lowerCamelCase__ ) return list(lowerCamelCase__ ) @require_torch @require_vision class A_ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any]): # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] ,image_std=[0.5, 0.5, 0.5]) if is_vision_available() else None ) @slow def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = VideoMAEForVideoClassification.from_pretrained('MCG-NJU/videomae-base-finetuned-kinetics').to( SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.default_image_processor __lowerCamelCase : int = prepare_video() __lowerCamelCase : str = image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__) # forward pass with torch.no_grad(): __lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Union[str, Any] = torch.Size((1, 4_0_0)) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = torch.tensor([0.3669, -0.0688, -0.2421]).to(SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) @slow def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short').to(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.default_image_processor __lowerCamelCase : List[str] = prepare_video() __lowerCamelCase : List[Any] = image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__) # add boolean mask, indicating which patches to mask __lowerCamelCase : str = hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos' ,filename='bool_masked_pos.pt') __lowerCamelCase : Dict = torch.load(SCREAMING_SNAKE_CASE__) # forward pass with torch.no_grad(): __lowerCamelCase : Optional[Any] = model(**SCREAMING_SNAKE_CASE__) # verify the logits __lowerCamelCase : Any = torch.Size([1, 1_4_0_8, 1_5_3_6]) __lowerCamelCase : Optional[int] = torch.tensor( [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] ,device=SCREAMING_SNAKE_CASE__) self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify the loss (`config.norm_pix_loss` = `True`) __lowerCamelCase : Any = torch.tensor([0.5142] ,device=SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.loss ,SCREAMING_SNAKE_CASE__ ,atol=1E-4)) # verify the loss (`config.norm_pix_loss` = `False`) __lowerCamelCase : List[Any] = VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short' ,norm_pix_loss=SCREAMING_SNAKE_CASE__).to( SCREAMING_SNAKE_CASE__) with torch.no_grad(): __lowerCamelCase : Optional[int] = model(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = torch.tensor(torch.tensor([0.6469]) ,device=SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.loss ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
1
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: assert isinstance(lowerCamelCase__ , lowerCamelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : str = tmp_path / 'cache' __lowerCamelCase : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __lowerCamelCase : Tuple = ParquetDatasetReader(lowerCamelCase__ , cache_dir=lowerCamelCase__ , keep_in_memory=lowerCamelCase__ ).read() _check_parquet_dataset(lowerCamelCase__ , lowerCamelCase__ ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : Union[str, Any] = tmp_path / 'cache' __lowerCamelCase : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __lowerCamelCase : Union[str, Any] = features.copy() if features else default_expected_features __lowerCamelCase : Union[str, Any] = ( Features({feature: Value(lowerCamelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __lowerCamelCase : Dict = ParquetDatasetReader(lowerCamelCase__ , features=lowerCamelCase__ , cache_dir=lowerCamelCase__ ).read() _check_parquet_dataset(lowerCamelCase__ , lowerCamelCase__ ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: __lowerCamelCase : Union[str, Any] = tmp_path / 'cache' __lowerCamelCase : Optional[int] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __lowerCamelCase : Tuple = ParquetDatasetReader(lowerCamelCase__ , cache_dir=lowerCamelCase__ , split=lowerCamelCase__ ).read() _check_parquet_dataset(lowerCamelCase__ , lowerCamelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: if issubclass(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Optional[int] = parquet_path elif issubclass(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Dict = [parquet_path] __lowerCamelCase : List[Any] = tmp_path / 'cache' __lowerCamelCase : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __lowerCamelCase : Dict = ParquetDatasetReader(lowerCamelCase__ , cache_dir=lowerCamelCase__ ).read() _check_parquet_dataset(lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=("train",) ) -> List[str]: assert isinstance(lowerCamelCase__ , lowerCamelCase__ ) for split in splits: __lowerCamelCase : Dict = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Union[str, Any] = tmp_path / 'cache' __lowerCamelCase : int = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __lowerCamelCase : List[str] = ParquetDatasetReader( {'train': parquet_path} , cache_dir=lowerCamelCase__ , keep_in_memory=lowerCamelCase__ ).read() _check_parquet_datasetdict(lowerCamelCase__ , lowerCamelCase__ ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: __lowerCamelCase : Tuple = tmp_path / 'cache' __lowerCamelCase : List[Any] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __lowerCamelCase : List[str] = features.copy() if features else default_expected_features __lowerCamelCase : str = ( Features({feature: Value(lowerCamelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) __lowerCamelCase : Union[str, Any] = ParquetDatasetReader({'train': parquet_path} , features=lowerCamelCase__ , cache_dir=lowerCamelCase__ ).read() _check_parquet_datasetdict(lowerCamelCase__ , lowerCamelCase__ ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: if split: __lowerCamelCase : List[str] = {split: parquet_path} else: __lowerCamelCase : List[str] = 'train' __lowerCamelCase : List[Any] = {'train': parquet_path, 'test': parquet_path} __lowerCamelCase : Tuple = tmp_path / 'cache' __lowerCamelCase : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __lowerCamelCase : Optional[Any] = ParquetDatasetReader(lowerCamelCase__ , cache_dir=lowerCamelCase__ ).read() _check_parquet_datasetdict(lowerCamelCase__ , lowerCamelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: __lowerCamelCase : Union[str, Any] = ParquetDatasetWriter(lowerCamelCase__ , tmp_path / 'foo.parquet' ) assert writer.write() > 0 __lowerCamelCase : Union[str, Any] = pq.ParquetFile(tmp_path / 'foo.parquet' ) __lowerCamelCase : List[str] = pf.read() assert dataset.data.table == output_table def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : List[str] = str(shared_datadir / 'test_image_rgb.jpg' ) __lowerCamelCase : Optional[int] = {'image': [image_path]} __lowerCamelCase : int = Features({'image': Image()} ) __lowerCamelCase : Union[str, Any] = Dataset.from_dict(lowerCamelCase__ , features=lowerCamelCase__ ) __lowerCamelCase : Any = ParquetDatasetWriter(lowerCamelCase__ , tmp_path / 'foo.parquet' ) assert writer.write() > 0 __lowerCamelCase : int = Dataset.from_parquet(str(tmp_path / 'foo.parquet' ) ) assert dataset.features == reloaded_dataset.features __lowerCamelCase : Dict = ParquetDatasetReader(str(tmp_path / 'foo.parquet' ) , streaming=lowerCamelCase__ ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( 'feature, expected' , [ (Features({'foo': Value('int32' )} ), None), (Features({'image': Image(), 'foo': Value('int32' )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({'nested': Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: assert get_writer_batch_size(lowerCamelCase__ ) == expected
73
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
1
import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class A_ : def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str=1_3 ,SCREAMING_SNAKE_CASE__ : List[str]=7 ,SCREAMING_SNAKE_CASE__ : int=True ,SCREAMING_SNAKE_CASE__ : List[str]=True ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Dict=9_9 ,SCREAMING_SNAKE_CASE__ : Tuple=6_4 ,SCREAMING_SNAKE_CASE__ : Any=3_2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5 ,SCREAMING_SNAKE_CASE__ : Optional[int]=4 ,SCREAMING_SNAKE_CASE__ : List[str]=3_7 ,SCREAMING_SNAKE_CASE__ : Dict="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Any=0.1 ,SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Any=1_6 ,SCREAMING_SNAKE_CASE__ : List[Any]=2 ,SCREAMING_SNAKE_CASE__ : str=0.02 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3 ,SCREAMING_SNAKE_CASE__ : List[str]=4 ,SCREAMING_SNAKE_CASE__ : Tuple=None ,): __lowerCamelCase : Optional[int] = parent __lowerCamelCase : Any = batch_size __lowerCamelCase : List[str] = seq_length __lowerCamelCase : List[str] = is_training __lowerCamelCase : int = use_input_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : Dict = vocab_size __lowerCamelCase : Optional[int] = hidden_size __lowerCamelCase : Union[str, Any] = embedding_size __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : int = num_attention_heads __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : Dict = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Optional[int] = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : List[Any] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : int = num_labels __lowerCamelCase : Optional[int] = num_choices __lowerCamelCase : Optional[Any] = scope def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Optional[Any] = None if self.use_input_mask: __lowerCamelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : List[str] = None if self.use_token_type_ids: __lowerCamelCase : int = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size) __lowerCamelCase : Dict = None __lowerCamelCase : Dict = None __lowerCamelCase : Tuple = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size) __lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels) __lowerCamelCase : Union[str, Any] = 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 lowerCAmelCase ( self : Optional[int]): return MegatronBertConfig( 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 ,embedding_size=self.embedding_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : str = MegatronBertModel(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size)) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str]): __lowerCamelCase : Any = MegatronBertForMaskedLM(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size)) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any]): __lowerCamelCase : int = MegatronBertForCausalLM(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : int = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size)) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : Optional[Any] = MegatronBertForNextSentencePrediction(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, 2)) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : Dict = MegatronBertForPreTraining(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Union[str, Any] = model( SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ,next_sentence_label=SCREAMING_SNAKE_CASE__ ,) self.parent.assertEqual(result.prediction_logits.shape ,(self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertEqual(result.seq_relationship_logits.shape ,(self.batch_size, 2)) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = MegatronBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Union[str, Any] = model( SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,start_positions=SCREAMING_SNAKE_CASE__ ,end_positions=SCREAMING_SNAKE_CASE__ ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length)) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : int = self.num_labels __lowerCamelCase : Tuple = MegatronBertForSequenceClassification(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels)) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : int = self.num_labels __lowerCamelCase : Dict = MegatronBertForTokenClassification(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Dict = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels)) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : Dict = self.num_choices __lowerCamelCase : Optional[Any] = MegatronBertForMultipleChoice(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() __lowerCamelCase : Tuple = input_ids.unsqueeze(1).expand(-1 ,self.num_choices ,-1).contiguous() __lowerCamelCase : Any = token_type_ids.unsqueeze(1).expand(-1 ,self.num_choices ,-1).contiguous() __lowerCamelCase : int = input_mask.unsqueeze(1).expand(-1 ,self.num_choices ,-1).contiguous() __lowerCamelCase : Union[str, Any] = model( SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices)) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Optional[int] = config_and_inputs __lowerCamelCase : str = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : List[str] = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) _UpperCAmelCase : Union[str, Any] = ( { '''feature-extraction''': MegatronBertModel, '''fill-mask''': MegatronBertForMaskedLM, '''question-answering''': MegatronBertForQuestionAnswering, '''text-classification''': MegatronBertForSequenceClassification, '''text-generation''': MegatronBertForCausalLM, '''token-classification''': MegatronBertForTokenClassification, '''zero-shot''': MegatronBertForSequenceClassification, } if is_torch_available() else {} ) _UpperCAmelCase : Union[str, Any] = True # test_resize_embeddings = False _UpperCAmelCase : List[Any] = False def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Any ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=False): __lowerCamelCase : Dict = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,return_labels=SCREAMING_SNAKE_CASE__) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=SCREAMING_SNAKE_CASE__) return inputs_dict def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : str = MegatronBertModelTester(self) __lowerCamelCase : Tuple = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,hidden_size=3_7) def lowerCAmelCase ( self : Optional[int]): self.config_tester.run_common_tests() def lowerCAmelCase ( self : Any): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any): __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*SCREAMING_SNAKE_CASE__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: return torch.tensor( lowerCamelCase__ , dtype=torch.long , device=lowerCamelCase__ , ) a =1E-4 @require_torch @require_sentencepiece @require_tokenizers class A_ ( unittest.TestCase ): @slow @unittest.skip('Model is not available.') def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Optional[Any] = 'nvidia/megatron-bert-uncased-345m' if "MYDIR" in os.environ: __lowerCamelCase : Optional[Any] = os.path.join(os.environ['MYDIR'] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = MegatronBertModel.from_pretrained(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.half() __lowerCamelCase : List[str] = _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]]) with torch.no_grad(): __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : List[Any] = torch.Size((1, 9, 1_0_2_4)) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3): for jj in range(3): __lowerCamelCase : int = output[0, ii, jj] __lowerCamelCase : Dict = expected[3 * ii + jj] __lowerCamelCase : List[Any] = 'ii={} jj={} a={} b={}'.format(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) self.assertTrue(math.isclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,rel_tol=SCREAMING_SNAKE_CASE__ ,abs_tol=SCREAMING_SNAKE_CASE__) ,msg=SCREAMING_SNAKE_CASE__)
73
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): 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 ,SCREAMING_SNAKE_CASE__) * ((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(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[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 lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): 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 : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,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
73
1
import logging import os import threading import time try: import warnings except ImportError: a =None try: import msvcrt except ImportError: a =None try: import fcntl except ImportError: a =None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: a =OSError # Data # ------------------------------------------------ a =[ """Timeout""", """BaseFileLock""", """WindowsFileLock""", """UnixFileLock""", """SoftFileLock""", """FileLock""", ] a ="""3.0.12""" a =None def SCREAMING_SNAKE_CASE__ ( ) -> int: global _logger __lowerCamelCase : int = _logger or logging.getLogger(__name__ ) return _logger class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Any = lock_file return None def __str__( self : Dict): __lowerCamelCase : int = F"The file lock '{self.lock_file}' could not be acquired." return temp class A_ : def __init__( self : int ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[Any] = lock return None def __enter__( self : Optional[Any]): return self.lock def __exit__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Any): self.lock.release() return None class A_ : def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=-1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None): __lowerCamelCase : str = max_filename_length if max_filename_length is not None else 2_5_5 # Hash the filename if it's too long __lowerCamelCase : Dict = self.hash_filename_if_too_long(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # The path to the lock file. __lowerCamelCase : int = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __lowerCamelCase : Dict = None # The default timeout value. __lowerCamelCase : List[Any] = timeout # We use this lock primarily for the lock counter. __lowerCamelCase : List[Any] = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __lowerCamelCase : Any = 0 return None @property def lowerCAmelCase ( self : Optional[int]): return self._lock_file @property def lowerCAmelCase ( self : Dict): return self._timeout @timeout.setter def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Tuple): __lowerCamelCase : Union[str, Any] = float(SCREAMING_SNAKE_CASE__) return None def lowerCAmelCase ( self : List[str]): raise NotImplementedError() def lowerCAmelCase ( self : List[Any]): raise NotImplementedError() @property def lowerCAmelCase ( self : Optional[Any]): return self._lock_file_fd is not None def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : int=0.05): # Use the default timeout, if no timeout is provided. if timeout is None: __lowerCamelCase : str = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __lowerCamelCase : Any = id(self) __lowerCamelCase : Optional[int] = self._lock_file __lowerCamelCase : str = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F"Attempting to acquire lock {lock_id} on {lock_filename}") self._acquire() if self.is_locked: logger().debug(F"Lock {lock_id} acquired on {lock_filename}") break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F"Timeout on acquiring lock {lock_id} on {lock_filename}") raise Timeout(self._lock_file) else: logger().debug( F"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...") time.sleep(SCREAMING_SNAKE_CASE__) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __lowerCamelCase : str = max(0 ,self._lock_counter - 1) raise return _Acquire_ReturnProxy(lock=self) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]=False): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __lowerCamelCase : str = id(self) __lowerCamelCase : int = self._lock_file logger().debug(F"Attempting to release lock {lock_id} on {lock_filename}") self._release() __lowerCamelCase : Optional[int] = 0 logger().debug(F"Lock {lock_id} released on {lock_filename}") return None def __enter__( self : List[Any]): self.acquire() return self def __exit__( self : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict): self.release() return None def __del__( self : List[Any]): self.release(force=SCREAMING_SNAKE_CASE__) return None def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = os.path.basename(SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > max_length and max_length > 0: __lowerCamelCase : Optional[int] = os.path.dirname(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = str(hash(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = filename[: max_length - len(SCREAMING_SNAKE_CASE__) - 8] + '...' + hashed_filename + '.lock' return os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else: return path class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=-1 ,SCREAMING_SNAKE_CASE__ : Any=None): from .file_utils import relative_to_absolute_path super().__init__(SCREAMING_SNAKE_CASE__ ,timeout=SCREAMING_SNAKE_CASE__ ,max_filename_length=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = '\\\\?\\' + relative_to_absolute_path(self.lock_file) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Tuple = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __lowerCamelCase : List[Any] = os.open(self._lock_file ,SCREAMING_SNAKE_CASE__) except OSError: pass else: try: msvcrt.locking(SCREAMING_SNAKE_CASE__ ,msvcrt.LK_NBLCK ,1) except OSError: os.close(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : Optional[Any] = fd return None def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : List[Any] = self._lock_file_fd __lowerCamelCase : Optional[Any] = None msvcrt.locking(SCREAMING_SNAKE_CASE__ ,msvcrt.LK_UNLCK ,1) os.close(SCREAMING_SNAKE_CASE__) try: os.remove(self._lock_file) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Tuple=-1 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=None): __lowerCamelCase : int = os.statvfs(os.path.dirname(SCREAMING_SNAKE_CASE__)).f_namemax super().__init__(SCREAMING_SNAKE_CASE__ ,timeout=SCREAMING_SNAKE_CASE__ ,max_filename_length=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : int = os.O_RDWR | os.O_CREAT | os.O_TRUNC __lowerCamelCase : List[str] = os.open(self._lock_file ,SCREAMING_SNAKE_CASE__) try: fcntl.flock(SCREAMING_SNAKE_CASE__ ,fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: os.close(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : List[Any] = fd return None def lowerCAmelCase ( self : List[Any]): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition __lowerCamelCase : List[Any] = self._lock_file_fd __lowerCamelCase : Optional[int] = None fcntl.flock(SCREAMING_SNAKE_CASE__ ,fcntl.LOCK_UN) os.close(SCREAMING_SNAKE_CASE__) return None class A_ ( SCREAMING_SNAKE_CASE ): def lowerCAmelCase ( self : Tuple): __lowerCamelCase : Optional[int] = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __lowerCamelCase : int = os.open(self._lock_file ,SCREAMING_SNAKE_CASE__) except OSError: pass else: __lowerCamelCase : Dict = fd return None def lowerCAmelCase ( self : Optional[Any]): os.close(self._lock_file_fd) __lowerCamelCase : str = None try: os.remove(self._lock_file) # The file is already deleted and that's what we want. except OSError: pass return None a =None if msvcrt: a =WindowsFileLock elif fcntl: a =UnixFileLock else: a =SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
73
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
1
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a =logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Path ,SCREAMING_SNAKE_CASE__ : Union[str, None] = None ,SCREAMING_SNAKE_CASE__ : Union[List[str], None] = None ,SCREAMING_SNAKE_CASE__ : Union[str, List[str], None] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[Any] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__))] if identifier is not None: __lowerCamelCase : Optional[Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): for n_ in n_identifier: __lowerCamelCase : int = [file for file in files if n_ not in file] else: __lowerCamelCase : List[str] = [file for file in files if n_identifier not in file] __lowerCamelCase : Any = ignore_files or [] ignore_files.append('__init__.py') __lowerCamelCase : Dict = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,SCREAMING_SNAKE_CASE__) if only_modules: __lowerCamelCase : List[Any] = file.split('.')[0] try: __lowerCamelCase : Optional[Any] = getattr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__) self.assertIs(len(result.failures) ,0) except AttributeError: logger.info(F"{module_identifier} is not a module.") else: __lowerCamelCase : Union[str, Any] = doctest.testfile(str('..' / directory / file) ,optionflags=doctest.ELLIPSIS) self.assertIs(result.failed ,0) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : List[Any] = 'modeling' __lowerCamelCase : int = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : int = Path('src/transformers') __lowerCamelCase : Any = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : List[Any] = Path('src/transformers') __lowerCamelCase : Tuple = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ ,identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Any = Path('src/transformers') __lowerCamelCase : Optional[int] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,n_identifier=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Dict): __lowerCamelCase : List[str] = Path('docs/source') __lowerCamelCase : int = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ ,ignore_files=SCREAMING_SNAKE_CASE__ ,only_modules=SCREAMING_SNAKE_CASE__)
73
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
1
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) a ={ """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""", } a ={ """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""", } a ={ """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""", } a ={ """num_train_timesteps""": 40, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } a ={ """num_train_timesteps""": 201, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } a ={ """num_train_timesteps""": 151, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[int]: if isinstance(lowerCamelCase__ , lowerCamelCase__ ): 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 SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ) -> Tuple: __lowerCamelCase : List[str] = checkpoint[F"{old_prefix}.in_layers.0.weight"] __lowerCamelCase : Any = checkpoint[F"{old_prefix}.in_layers.0.bias"] __lowerCamelCase : Optional[int] = checkpoint[F"{old_prefix}.in_layers.2.weight"] __lowerCamelCase : Tuple = checkpoint[F"{old_prefix}.in_layers.2.bias"] __lowerCamelCase : Optional[Any] = checkpoint[F"{old_prefix}.emb_layers.1.weight"] __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.emb_layers.1.bias"] __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.out_layers.0.weight"] __lowerCamelCase : str = checkpoint[F"{old_prefix}.out_layers.0.bias"] __lowerCamelCase : Optional[Any] = checkpoint[F"{old_prefix}.out_layers.3.weight"] __lowerCamelCase : Optional[int] = checkpoint[F"{old_prefix}.out_layers.3.bias"] if has_skip: __lowerCamelCase : str = checkpoint[F"{old_prefix}.skip_connection.weight"] __lowerCamelCase : Optional[int] = checkpoint[F"{old_prefix}.skip_connection.bias"] return new_checkpoint def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> Tuple: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = checkpoint[F"{old_prefix}.qkv.weight"].chunk(3 , dim=0 ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.qkv.bias"].chunk(3 , dim=0 ) __lowerCamelCase : int = checkpoint[F"{old_prefix}.norm.weight"] __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.norm.bias"] __lowerCamelCase : Dict = weight_q.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : int = bias_q.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Optional[Any] = weight_k.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Any = bias_k.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Tuple = weight_v.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Any = bias_v.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Union[str, Any] = ( checkpoint[F"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) __lowerCamelCase : Union[str, Any] = checkpoint[F"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : int = torch.load(lowerCamelCase__ , map_location='cpu' ) __lowerCamelCase : Optional[int] = {} __lowerCamelCase : Dict = checkpoint['time_embed.0.weight'] __lowerCamelCase : Optional[Any] = checkpoint['time_embed.0.bias'] __lowerCamelCase : Dict = checkpoint['time_embed.2.weight'] __lowerCamelCase : int = checkpoint['time_embed.2.bias'] if unet_config["num_class_embeds"] is not None: __lowerCamelCase : Optional[Any] = checkpoint['label_emb.weight'] __lowerCamelCase : str = checkpoint['input_blocks.0.0.weight'] __lowerCamelCase : List[Any] = checkpoint['input_blocks.0.0.bias'] __lowerCamelCase : Tuple = unet_config['down_block_types'] __lowerCamelCase : Optional[Any] = unet_config['layers_per_block'] __lowerCamelCase : Any = unet_config['attention_head_dim'] __lowerCamelCase : Any = unet_config['block_out_channels'] __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : Tuple = channels_list[0] for i, layer_type in enumerate(lowerCamelCase__ ): __lowerCamelCase : str = channels_list[i] __lowerCamelCase : List[str] = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(lowerCamelCase__ ): __lowerCamelCase : List[Any] = F"down_blocks.{i}.resnets.{j}" __lowerCamelCase : int = F"input_blocks.{current_layer}.0" __lowerCamelCase : int = True if j == 0 and downsample_block_has_skip else False __lowerCamelCase : List[Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = F"down_blocks.{i}.resnets.{j}" __lowerCamelCase : Optional[int] = F"input_blocks.{current_layer}.0" __lowerCamelCase : Optional[Any] = True if j == 0 and downsample_block_has_skip else False __lowerCamelCase : List[Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) __lowerCamelCase : Any = F"down_blocks.{i}.attentions.{j}" __lowerCamelCase : Union[str, Any] = F"input_blocks.{current_layer}.1" __lowerCamelCase : List[Any] = convert_attention( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) current_layer += 1 if i != len(lowerCamelCase__ ) - 1: __lowerCamelCase : Tuple = F"down_blocks.{i}.downsamplers.0" __lowerCamelCase : Any = F"input_blocks.{current_layer}.0" __lowerCamelCase : Any = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) current_layer += 1 __lowerCamelCase : Union[str, Any] = current_channels # hardcoded the mid-block for now __lowerCamelCase : Optional[Any] = 'mid_block.resnets.0' __lowerCamelCase : Any = 'middle_block.0' __lowerCamelCase : Any = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : str = 'mid_block.attentions.0' __lowerCamelCase : Union[str, Any] = 'middle_block.1' __lowerCamelCase : str = convert_attention(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 'mid_block.resnets.1' __lowerCamelCase : Optional[int] = 'middle_block.2' __lowerCamelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : str = 0 __lowerCamelCase : Union[str, Any] = unet_config['up_block_types'] for i, layer_type in enumerate(lowerCamelCase__ ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): __lowerCamelCase : Optional[int] = F"up_blocks.{i}.resnets.{j}" __lowerCamelCase : str = F"output_blocks.{current_layer}.0" __lowerCamelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) current_layer += 1 if i != len(lowerCamelCase__ ) - 1: __lowerCamelCase : List[str] = F"up_blocks.{i}.upsamplers.0" __lowerCamelCase : str = F"output_blocks.{current_layer-1}.1" __lowerCamelCase : Dict = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): __lowerCamelCase : Dict = F"up_blocks.{i}.resnets.{j}" __lowerCamelCase : int = F"output_blocks.{current_layer}.0" __lowerCamelCase : Optional[int] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) __lowerCamelCase : List[str] = F"up_blocks.{i}.attentions.{j}" __lowerCamelCase : Dict = F"output_blocks.{current_layer}.1" __lowerCamelCase : Dict = convert_attention( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) current_layer += 1 if i != len(lowerCamelCase__ ) - 1: __lowerCamelCase : int = F"up_blocks.{i}.upsamplers.0" __lowerCamelCase : str = F"output_blocks.{current_layer-1}.2" __lowerCamelCase : Optional[int] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = checkpoint['out.0.weight'] __lowerCamelCase : Dict = checkpoint['out.0.bias'] __lowerCamelCase : Optional[int] = checkpoint['out.2.weight'] __lowerCamelCase : List[str] = checkpoint['out.2.bias'] return new_checkpoint if __name__ == "__main__": a =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.""") a =parser.parse_args() a =strabool(args.class_cond) a =os.path.basename(args.unet_path) print(F"""Checkpoint: {ckpt_name}""") # Get U-Net config if "imagenet64" in ckpt_name: a =IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a =LSUN_256_UNET_CONFIG elif "test" in ckpt_name: a =TEST_UNET_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") if not args.class_cond: a =None a =con_pt_to_diffuser(args.unet_path, unet_config) a =UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: a =CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: a =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)): a =CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") a =CMStochasticIterativeScheduler(**scheduler_config) a =ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
73
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
1
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class A_ ( unittest.TestCase ): @property def lowerCAmelCase ( self : str): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCAmelCase ( self : Dict): __lowerCamelCase : Tuple = ort.SessionOptions() __lowerCamelCase : str = False return options def lowerCAmelCase ( self : Dict): __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png') __lowerCamelCase : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png') __lowerCamelCase : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy') # using the PNDM scheduler by default __lowerCamelCase : Tuple = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' ,revision='onnx' ,safety_checker=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = 'A red cat sitting on a park bench' __lowerCamelCase : Union[str, Any] = np.random.RandomState(0) __lowerCamelCase : Any = pipe( prompt=SCREAMING_SNAKE_CASE__ ,image=SCREAMING_SNAKE_CASE__ ,mask_image=SCREAMING_SNAKE_CASE__ ,strength=0.75 ,guidance_scale=7.5 ,num_inference_steps=1_5 ,generator=SCREAMING_SNAKE_CASE__ ,output_type='np' ,) __lowerCamelCase : Tuple = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image).max() < 1E-2
73
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
1
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="""%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s""", datefmt="""%Y-%m-%d %H:%M:%S""", level=os.environ.get("""LOGLEVEL""", """INFO""").upper(), stream=sys.stdout, ) a =logging.getLogger(__name__) a ={"""facebook/bart-base""": BartForConditionalGeneration} a ={"""facebook/bart-base""": BartTokenizer} def SCREAMING_SNAKE_CASE__ ( ) -> int: __lowerCamelCase : Dict = argparse.ArgumentParser(description='Export Bart model + Beam Search to ONNX graph.' ) parser.add_argument( '--validation_file' , type=lowerCamelCase__ , default=lowerCamelCase__ , help='A csv or a json file containing the validation data.' ) parser.add_argument( '--max_length' , type=lowerCamelCase__ , default=5 , help='The maximum total input sequence length after tokenization.' , ) parser.add_argument( '--num_beams' , type=lowerCamelCase__ , default=lowerCamelCase__ , help=( 'Number of beams to use for evaluation. This argument will be ' 'passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.' ) , ) parser.add_argument( '--model_name_or_path' , type=lowerCamelCase__ , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=lowerCamelCase__ , ) parser.add_argument( '--config_name' , type=lowerCamelCase__ , default=lowerCamelCase__ , help='Pretrained config name or path if not the same as model_name' , ) parser.add_argument( '--device' , type=lowerCamelCase__ , default='cpu' , help='Device where the model will be run' , ) parser.add_argument('--output_file_path' , type=lowerCamelCase__ , default=lowerCamelCase__ , help='Where to store the final ONNX file.' ) __lowerCamelCase : Optional[Any] = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__="cpu" ) -> Union[str, Any]: __lowerCamelCase : List[Any] = model_dict[model_name].from_pretrained(lowerCamelCase__ ).to(lowerCamelCase__ ) __lowerCamelCase : str = tokenizer_dict[model_name].from_pretrained(lowerCamelCase__ ) if model_name in ["facebook/bart-base"]: __lowerCamelCase : int = 0 __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = 0 return huggingface_model, tokenizer def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: model.eval() __lowerCamelCase : int = None __lowerCamelCase : str = torch.jit.script(BARTBeamSearchGenerator(lowerCamelCase__ ) ) with torch.no_grad(): __lowerCamelCase : Union[str, Any] = 'My friends are cool but they eat too many carbs.' __lowerCamelCase : Union[str, Any] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1_0_2_4 , return_tensors='pt' ).to(model.device ) __lowerCamelCase : Tuple = model.generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , num_beams=lowerCamelCase__ , max_length=lowerCamelCase__ , early_stopping=lowerCamelCase__ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowerCamelCase__ , ( inputs['input_ids'], inputs['attention_mask'], num_beams, max_length, model.config.decoder_start_token_id, ) , lowerCamelCase__ , opset_version=1_4 , input_names=['input_ids', 'attention_mask', 'num_beams', 'max_length', 'decoder_start_token_id'] , output_names=['output_ids'] , dynamic_axes={ 'input_ids': {0: 'batch', 1: 'seq'}, 'output_ids': {0: 'batch', 1: 'seq_out'}, } , example_outputs=lowerCamelCase__ , ) logger.info('Model exported to {}'.format(lowerCamelCase__ ) ) __lowerCamelCase : Dict = remove_dup_initializers(os.path.abspath(lowerCamelCase__ ) ) logger.info('Deduplicated and optimized model written to {}'.format(lowerCamelCase__ ) ) __lowerCamelCase : Dict = onnxruntime.InferenceSession(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ort_sess.run( lowerCamelCase__ , { 'input_ids': inputs['input_ids'].cpu().numpy(), 'attention_mask': inputs['attention_mask'].cpu().numpy(), 'num_beams': np.array(lowerCamelCase__ ), 'max_length': np.array(lowerCamelCase__ ), 'decoder_start_token_id': np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 ) logger.info('Model outputs from torch and ONNX Runtime are similar.' ) logger.info('Success.' ) def SCREAMING_SNAKE_CASE__ ( ) -> Union[str, Any]: __lowerCamelCase : str = parse_args() __lowerCamelCase : List[str] = 5 __lowerCamelCase : Any = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() __lowerCamelCase : Dict = torch.device(args.device ) __lowerCamelCase , __lowerCamelCase : Tuple = load_model_tokenizer(args.model_name_or_path , lowerCamelCase__ ) if model.config.decoder_start_token_id is None: raise ValueError('Make sure that `config.decoder_start_token_id` is correctly defined' ) model.to(lowerCamelCase__ ) if args.max_length: __lowerCamelCase : Optional[int] = args.max_length if args.num_beams: __lowerCamelCase : int = args.num_beams if args.output_file_path: __lowerCamelCase : Any = args.output_file_path else: __lowerCamelCase : Dict = 'BART.onnx' logger.info('Exporting model to ONNX' ) export_and_validate_model(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": main()
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : List[Any] = hex_num.strip() if not hex_num: raise ValueError('No value was passed to the function' ) __lowerCamelCase : List[Any] = hex_num[0] == '-' if is_negative: __lowerCamelCase : Dict = hex_num[1:] try: __lowerCamelCase : List[str] = int(lowerCamelCase__ , 1_6 ) except ValueError: raise ValueError('Invalid value was passed to the function' ) __lowerCamelCase : Tuple = '' while int_num > 0: __lowerCamelCase : List[Any] = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('-' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
73
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 A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer a ={"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} a ={ """vocab_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt""" ), """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""", """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json""" ), """google/electra-base-generator""": ( """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json""" ), """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json""" ), }, } a ={ """google/electra-small-generator""": 512, """google/electra-base-generator""": 512, """google/electra-large-generator""": 512, """google/electra-small-discriminator""": 512, """google/electra-base-discriminator""": 512, """google/electra-large-discriminator""": 512, } a ={ """google/electra-small-generator""": {"""do_lower_case""": True}, """google/electra-base-generator""": {"""do_lower_case""": True}, """google/electra-large-generator""": {"""do_lower_case""": True}, """google/electra-small-discriminator""": {"""do_lower_case""": True}, """google/electra-base-discriminator""": {"""do_lower_case""": True}, """google/electra-large-discriminator""": {"""do_lower_case""": True}, } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES _UpperCAmelCase : str = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : List[str] = PRETRAINED_INIT_CONFIGURATION _UpperCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Union[str, Any] = ElectraTokenizer def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[int]="[UNK]" ,SCREAMING_SNAKE_CASE__ : int="[SEP]" ,SCREAMING_SNAKE_CASE__ : Tuple="[PAD]" ,SCREAMING_SNAKE_CASE__ : Dict="[CLS]" ,SCREAMING_SNAKE_CASE__ : Dict="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : List[str]=None ,**SCREAMING_SNAKE_CASE__ : Dict ,): super().__init__( SCREAMING_SNAKE_CASE__ ,tokenizer_file=SCREAMING_SNAKE_CASE__ ,do_lower_case=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ ,strip_accents=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('lowercase' ,SCREAMING_SNAKE_CASE__) != do_lower_case or normalizer_state.get('strip_accents' ,SCREAMING_SNAKE_CASE__) != strip_accents or normalizer_state.get('handle_chinese_chars' ,SCREAMING_SNAKE_CASE__) != tokenize_chinese_chars ): __lowerCamelCase : Union[str, Any] = getattr(SCREAMING_SNAKE_CASE__ ,normalizer_state.pop('type')) __lowerCamelCase : List[Any] = do_lower_case __lowerCamelCase : Optional[int] = strip_accents __lowerCamelCase : Dict = tokenize_chinese_chars __lowerCamelCase : Tuple = normalizer_class(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = do_lower_case def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int]=None): __lowerCamelCase : Union[str, Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : int = [self.sep_token_id] __lowerCamelCase : List[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 lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): __lowerCamelCase : int = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ ,name=SCREAMING_SNAKE_CASE__) return tuple(SCREAMING_SNAKE_CASE__)
73
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : torch.FloatTensor class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): @register_to_config def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int = 3_2 ,SCREAMING_SNAKE_CASE__ : int = 6_4 ,SCREAMING_SNAKE_CASE__ : int = 2_0 ,SCREAMING_SNAKE_CASE__ : int = 7_6_8 ,SCREAMING_SNAKE_CASE__ : Any=7_7 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : str = "silu" ,SCREAMING_SNAKE_CASE__ : Optional[str] = None ,SCREAMING_SNAKE_CASE__ : Optional[str] = None ,SCREAMING_SNAKE_CASE__ : Optional[str] = "linear" ,SCREAMING_SNAKE_CASE__ : Optional[str] = "prd" ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,): super().__init__() __lowerCamelCase : Optional[Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = attention_head_dim __lowerCamelCase : Tuple = num_attention_heads * attention_head_dim __lowerCamelCase : List[Any] = additional_embeddings __lowerCamelCase : List[str] = time_embed_dim or inner_dim __lowerCamelCase : Union[str, Any] = embedding_proj_dim or embedding_dim __lowerCamelCase : Optional[int] = clip_embed_dim or embedding_dim __lowerCamelCase : Tuple = Timesteps(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,0) __lowerCamelCase : int = TimestepEmbedding(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,out_dim=SCREAMING_SNAKE_CASE__ ,act_fn=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if embedding_proj_norm_type is None: __lowerCamelCase : List[Any] = None elif embedding_proj_norm_type == "layer": __lowerCamelCase : Any = nn.LayerNorm(SCREAMING_SNAKE_CASE__) else: raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}") __lowerCamelCase : Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if encoder_hid_proj_type is None: __lowerCamelCase : Union[str, Any] = None elif encoder_hid_proj_type == "linear": __lowerCamelCase : Any = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else: raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}") __lowerCamelCase : Dict = nn.Parameter(torch.zeros(1 ,num_embeddings + additional_embeddings ,SCREAMING_SNAKE_CASE__)) if added_emb_type == "prd": __lowerCamelCase : int = nn.Parameter(torch.zeros(1 ,1 ,SCREAMING_SNAKE_CASE__)) elif added_emb_type is None: __lowerCamelCase : Dict = None else: raise ValueError( F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`.") __lowerCamelCase : List[Any] = nn.ModuleList( [ BasicTransformerBlock( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,dropout=SCREAMING_SNAKE_CASE__ ,activation_fn='gelu' ,attention_bias=SCREAMING_SNAKE_CASE__ ,) for d in range(SCREAMING_SNAKE_CASE__) ]) if norm_in_type == "layer": __lowerCamelCase : List[str] = nn.LayerNorm(SCREAMING_SNAKE_CASE__) elif norm_in_type is None: __lowerCamelCase : Tuple = None else: raise ValueError(F"Unsupported norm_in_type: {norm_in_type}.") __lowerCamelCase : Any = nn.LayerNorm(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = nn.Linear(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] ,-10000.0) causal_attention_mask.triu_(1) __lowerCamelCase : Union[str, Any] = causal_attention_mask[None, ...] self.register_buffer('causal_attention_mask' ,SCREAMING_SNAKE_CASE__ ,persistent=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = nn.Parameter(torch.zeros(1 ,SCREAMING_SNAKE_CASE__)) __lowerCamelCase : str = nn.Parameter(torch.zeros(1 ,SCREAMING_SNAKE_CASE__)) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Tuple = {} def fn_recursive_add_processors(SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : torch.nn.Module ,SCREAMING_SNAKE_CASE__ : Dict[str, AttentionProcessor]): if hasattr(SCREAMING_SNAKE_CASE__ ,'set_processor'): __lowerCamelCase : Union[str, Any] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) return processors for name, module in self.named_children(): fn_recursive_add_processors(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) return processors def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Union[AttentionProcessor, Dict[str, AttentionProcessor]]): __lowerCamelCase : List[Any] = len(self.attn_processors.keys()) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) and len(SCREAMING_SNAKE_CASE__) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(SCREAMING_SNAKE_CASE__)} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes.") def fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : torch.nn.Module ,SCREAMING_SNAKE_CASE__ : Tuple): if hasattr(SCREAMING_SNAKE_CASE__ ,'set_processor'): if not isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): module.set_processor(SCREAMING_SNAKE_CASE__) else: module.set_processor(processor.pop(F"{name}.processor")) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) for name, module in self.named_children(): fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): self.set_attn_processor(AttnProcessor()) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Union[torch.Tensor, float, int] ,SCREAMING_SNAKE_CASE__ : torch.FloatTensor ,SCREAMING_SNAKE_CASE__ : Optional[torch.FloatTensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.BoolTensor] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,): __lowerCamelCase : List[str] = hidden_states.shape[0] __lowerCamelCase : int = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = torch.tensor([timesteps] ,dtype=torch.long ,device=hidden_states.device) elif torch.is_tensor(SCREAMING_SNAKE_CASE__) and len(timesteps.shape) == 0: __lowerCamelCase : int = timesteps[None].to(hidden_states.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __lowerCamelCase : str = timesteps * torch.ones(SCREAMING_SNAKE_CASE__ ,dtype=timesteps.dtype ,device=timesteps.device) __lowerCamelCase : Optional[int] = self.time_proj(SCREAMING_SNAKE_CASE__) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __lowerCamelCase : str = timesteps_projected.to(dtype=self.dtype) __lowerCamelCase : Dict = self.time_embedding(SCREAMING_SNAKE_CASE__) if self.embedding_proj_norm is not None: __lowerCamelCase : Optional[Any] = self.embedding_proj_norm(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.embedding_proj(SCREAMING_SNAKE_CASE__) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __lowerCamelCase : Optional[Any] = self.encoder_hidden_states_proj(SCREAMING_SNAKE_CASE__) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError('`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set') __lowerCamelCase : Optional[Any] = self.proj_in(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = self.positional_embedding.to(hidden_states.dtype) __lowerCamelCase : Tuple = [] __lowerCamelCase : Optional[Any] = 0 if encoder_hidden_states is not None: additional_embeds.append(SCREAMING_SNAKE_CASE__) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape) == 2: __lowerCamelCase : int = proj_embeddings[:, None, :] if len(hidden_states.shape) == 2: __lowerCamelCase : int = hidden_states[:, None, :] __lowerCamelCase : List[str] = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __lowerCamelCase : Any = self.prd_embedding.to(hidden_states.dtype).expand(SCREAMING_SNAKE_CASE__ ,-1 ,-1) additional_embeds.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = torch.cat( SCREAMING_SNAKE_CASE__ ,dim=1 ,) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __lowerCamelCase : Any = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __lowerCamelCase : Tuple = F.pad( SCREAMING_SNAKE_CASE__ ,( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) ,value=0.0 ,) __lowerCamelCase : Optional[Any] = hidden_states + positional_embeddings if attention_mask is not None: __lowerCamelCase : Dict = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0 __lowerCamelCase : int = F.pad(SCREAMING_SNAKE_CASE__ ,(0, self.additional_embeddings) ,value=0.0) __lowerCamelCase : List[Any] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype) __lowerCamelCase : List[str] = attention_mask.repeat_interleave(self.config.num_attention_heads ,dim=0) if self.norm_in is not None: __lowerCamelCase : Union[str, Any] = self.norm_in(SCREAMING_SNAKE_CASE__) for block in self.transformer_blocks: __lowerCamelCase : List[Any] = block(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.norm_out(SCREAMING_SNAKE_CASE__) if self.prd_embedding is not None: __lowerCamelCase : Dict = hidden_states[:, -1] else: __lowerCamelCase : Union[str, Any] = hidden_states[:, additional_embeddings_len:] __lowerCamelCase : int = self.proj_to_clip_embeddings(SCREAMING_SNAKE_CASE__) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
73
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
1
import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging a =logging.get_logger(__name__) # pylint: disable=invalid-name class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : WhisperForConditionalGeneration ,SCREAMING_SNAKE_CASE__ : WhisperProcessor ,SCREAMING_SNAKE_CASE__ : AutoencoderKL ,SCREAMING_SNAKE_CASE__ : CLIPTextModel ,SCREAMING_SNAKE_CASE__ : CLIPTokenizer ,SCREAMING_SNAKE_CASE__ : UNetaDConditionModel ,SCREAMING_SNAKE_CASE__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] ,SCREAMING_SNAKE_CASE__ : StableDiffusionSafetyChecker ,SCREAMING_SNAKE_CASE__ : CLIPImageProcessor ,): super().__init__() if safety_checker is None: logger.warning( F"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" ' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered' ' results in services or applications open to the public. Both the diffusers team and Hugging Face' ' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling' ' it only for use-cases that involve analyzing network behavior or auditing its results. For more' ' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .') self.register_modules( speech_model=SCREAMING_SNAKE_CASE__ ,speech_processor=SCREAMING_SNAKE_CASE__ ,vae=SCREAMING_SNAKE_CASE__ ,text_encoder=SCREAMING_SNAKE_CASE__ ,tokenizer=SCREAMING_SNAKE_CASE__ ,unet=SCREAMING_SNAKE_CASE__ ,scheduler=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, int]] = "auto"): if slice_size == "auto": __lowerCamelCase : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str): self.enable_attention_slicing(SCREAMING_SNAKE_CASE__) @torch.no_grad() def __call__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict=1_6_0_0_0 ,SCREAMING_SNAKE_CASE__ : int = 5_1_2 ,SCREAMING_SNAKE_CASE__ : int = 5_1_2 ,SCREAMING_SNAKE_CASE__ : int = 5_0 ,SCREAMING_SNAKE_CASE__ : float = 7.5 ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, List[str]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : Optional[torch.Generator] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.FloatTensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[str] = "pil" ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,SCREAMING_SNAKE_CASE__ : int = 1 ,**SCREAMING_SNAKE_CASE__ : Any ,): __lowerCamelCase : Dict = self.speech_processor.feature_extractor( SCREAMING_SNAKE_CASE__ ,return_tensors='pt' ,sampling_rate=SCREAMING_SNAKE_CASE__).input_features.to(self.device) __lowerCamelCase : Dict = self.speech_model.generate(SCREAMING_SNAKE_CASE__ ,max_length=4_8_0_0_0_0) __lowerCamelCase : Optional[Any] = self.speech_processor.tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ,skip_special_tokens=SCREAMING_SNAKE_CASE__ ,normalize=SCREAMING_SNAKE_CASE__)[ 0 ] if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[Any] = 1 elif isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE__) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE__)}") if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}.") if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE__)}.") # get prompt text embeddings __lowerCamelCase : str = self.tokenizer( SCREAMING_SNAKE_CASE__ ,padding='max_length' ,max_length=self.tokenizer.model_max_length ,return_tensors='pt' ,) __lowerCamelCase : List[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __lowerCamelCase : Optional[int] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' F" {self.tokenizer.model_max_length} tokens: {removed_text}") __lowerCamelCase : Tuple = text_input_ids[:, : self.tokenizer.model_max_length] __lowerCamelCase : Optional[int] = self.text_encoder(text_input_ids.to(self.device))[0] # duplicate text embeddings for each generation per prompt, using mps friendly method __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : int = text_embeddings.shape __lowerCamelCase : Union[str, Any] = text_embeddings.repeat(1 ,SCREAMING_SNAKE_CASE__ ,1) __lowerCamelCase : Optional[int] = text_embeddings.view(bs_embed * num_images_per_prompt ,SCREAMING_SNAKE_CASE__ ,-1) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __lowerCamelCase : Union[str, Any] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __lowerCamelCase : List[str] if negative_prompt is None: __lowerCamelCase : Dict = [''] * batch_size elif type(SCREAMING_SNAKE_CASE__) is not type(SCREAMING_SNAKE_CASE__): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE__)} !=" F" {type(SCREAMING_SNAKE_CASE__)}.") elif isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Optional[int] = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE__): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE__)}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" ' the batch size of `prompt`.') else: __lowerCamelCase : str = negative_prompt __lowerCamelCase : Optional[int] = text_input_ids.shape[-1] __lowerCamelCase : List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE__ ,padding='max_length' ,max_length=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,return_tensors='pt' ,) __lowerCamelCase : Tuple = self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCamelCase : Optional[Any] = uncond_embeddings.shape[1] __lowerCamelCase : List[Any] = uncond_embeddings.repeat(1 ,SCREAMING_SNAKE_CASE__ ,1) __lowerCamelCase : str = uncond_embeddings.view(batch_size * num_images_per_prompt ,SCREAMING_SNAKE_CASE__ ,-1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __lowerCamelCase : List[Any] = torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __lowerCamelCase : Optional[int] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) __lowerCamelCase : int = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps __lowerCamelCase : Optional[int] = torch.randn(SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,device='cpu' ,dtype=SCREAMING_SNAKE_CASE__).to( self.device) else: __lowerCamelCase : Tuple = torch.randn(SCREAMING_SNAKE_CASE__ ,generator=SCREAMING_SNAKE_CASE__ ,device=self.device ,dtype=SCREAMING_SNAKE_CASE__) else: if latents.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}") __lowerCamelCase : List[str] = latents.to(self.device) # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand __lowerCamelCase : Union[str, Any] = self.scheduler.timesteps.to(self.device) # scale the initial noise by the standard deviation required by the scheduler __lowerCamelCase : int = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __lowerCamelCase : Any = 'eta' in set(inspect.signature(self.scheduler.step).parameters.keys()) __lowerCamelCase : Tuple = {} if accepts_eta: __lowerCamelCase : Any = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE__)): # expand the latents if we are doing classifier free guidance __lowerCamelCase : Dict = torch.cat([latents] * 2) if do_classifier_free_guidance else latents __lowerCamelCase : List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # predict the noise residual __lowerCamelCase : Any = self.unet(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,encoder_hidden_states=SCREAMING_SNAKE_CASE__).sample # perform guidance if do_classifier_free_guidance: __lowerCamelCase , __lowerCamelCase : Optional[int] = noise_pred.chunk(2) __lowerCamelCase : int = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 __lowerCamelCase : Tuple = self.scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = 1 / 0.18215 * latents __lowerCamelCase : List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE__).sample __lowerCamelCase : List[str] = (image / 2 + 0.5).clamp(0 ,1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __lowerCamelCase : Any = image.cpu().permute(0 ,2 ,3 ,1).float().numpy() if output_type == "pil": __lowerCamelCase : Optional[int] = self.numpy_to_pil(SCREAMING_SNAKE_CASE__) if not return_dict: return image return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE__ ,nsfw_content_detected=SCREAMING_SNAKE_CASE__)
73
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
1
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__=None , lowerCamelCase__=None ) -> Any: return field(default_factory=lambda: default , metadata=lowerCamelCase__ ) @dataclass class A_ : _UpperCAmelCase : str = field( metadata={'''help''': '''The csv file to plot.'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Disable logarithmic scale when plotting'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.''' } , ) _UpperCAmelCase : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''} , ) _UpperCAmelCase : Optional[List[str]] = list_field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: try: int(lowerCamelCase__ ) return True except ValueError: return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: try: float(lowerCamelCase__ ) return True except ValueError: return False class A_ : def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : str = args __lowerCamelCase : Any = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}) with open(self.args.csv_file ,newline='') as csv_file: __lowerCamelCase : Any = csv.DictReader(SCREAMING_SNAKE_CASE__) for row in reader: __lowerCamelCase : Any = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'])) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'])) if can_convert_to_int(row['result']): # value is not None __lowerCamelCase : Tuple = int(row['result']) elif can_convert_to_float(row['result']): # value is not None __lowerCamelCase : List[Any] = float(row['result']) def lowerCAmelCase ( self : List[str]): __lowerCamelCase , __lowerCamelCase : List[Any] = plt.subplots() __lowerCamelCase : Union[str, Any] = 'Time usage' if self.args.is_time else 'Memory usage' __lowerCamelCase : Optional[Any] = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log') ax.set_yscale('log') for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter()) for model_name_idx, model_name in enumerate(self.result_dict.keys()): __lowerCamelCase : int = sorted(set(self.result_dict[model_name]['bsz'])) __lowerCamelCase : Tuple = sorted(set(self.result_dict[model_name]['seq_len'])) __lowerCamelCase : int = self.result_dict[model_name]['result'] ((__lowerCamelCase) , (__lowerCamelCase)) : List[str] = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) __lowerCamelCase : List[str] = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: __lowerCamelCase : int = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] ,dtype=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Union[str, Any] = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] ,dtype=np.floataa ,) ((__lowerCamelCase) , (__lowerCamelCase)) : Optional[Any] = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) __lowerCamelCase : Tuple = np.asarray(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)[: len(SCREAMING_SNAKE_CASE__)] plt.scatter( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,label=F"{label_model_name} - {inner_loop_label}: {inner_loop_value}") plt.plot(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,'--') title_str += F" {label_model_name} vs." __lowerCamelCase : List[Any] = title_str[:-4] __lowerCamelCase : int = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(SCREAMING_SNAKE_CASE__) plt.xlabel(SCREAMING_SNAKE_CASE__) plt.ylabel(SCREAMING_SNAKE_CASE__) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file) else: plt.show() def SCREAMING_SNAKE_CASE__ ( ) -> Dict: __lowerCamelCase : Optional[Any] = HfArgumentParser(lowerCamelCase__ ) __lowerCamelCase : List[str] = parser.parse_args_into_dataclasses()[0] __lowerCamelCase : str = Plot(args=lowerCamelCase__ ) plot.plot() if __name__ == "__main__": main()
73
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[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 lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """MIT/ast-finetuned-audioset-10-10-0.4593""": ( """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = '''audio-spectrogram-transformer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int=7_6_8 ,SCREAMING_SNAKE_CASE__ : Any=1_2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 ,SCREAMING_SNAKE_CASE__ : str=3_0_7_2 ,SCREAMING_SNAKE_CASE__ : List[Any]="gelu" ,SCREAMING_SNAKE_CASE__ : Dict=0.0 ,SCREAMING_SNAKE_CASE__ : List[str]=0.0 ,SCREAMING_SNAKE_CASE__ : Dict=0.02 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=1E-12 ,SCREAMING_SNAKE_CASE__ : List[str]=1_6 ,SCREAMING_SNAKE_CASE__ : Any=True ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=1_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=1_0_2_4 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2_8 ,**SCREAMING_SNAKE_CASE__ : Any ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = hidden_size __lowerCamelCase : Any = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Optional[Any] = intermediate_size __lowerCamelCase : List[str] = hidden_act __lowerCamelCase : Tuple = hidden_dropout_prob __lowerCamelCase : str = attention_probs_dropout_prob __lowerCamelCase : Optional[int] = initializer_range __lowerCamelCase : Optional[int] = layer_norm_eps __lowerCamelCase : List[str] = patch_size __lowerCamelCase : int = qkv_bias __lowerCamelCase : Optional[int] = frequency_stride __lowerCamelCase : str = time_stride __lowerCamelCase : Dict = max_length __lowerCamelCase : List[Any] = num_mel_bins
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
from typing import List import numpy as np def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : List[Any] = {key: len(lowerCamelCase__ ) for key, value in gen_kwargs.items() if isinstance(lowerCamelCase__ , lowerCamelCase__ )} 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 : Union[str, Any] = max(lists_lengths.values() , default=0 ) return max(1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[range]: __lowerCamelCase : Tuple = [] for group_idx in range(lowerCamelCase__ ): __lowerCamelCase : List[str] = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break __lowerCamelCase : Tuple = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 __lowerCamelCase : str = range(lowerCamelCase__ , start + num_shards_to_add ) shards_indices_per_group.append(lowerCamelCase__ ) return shards_indices_per_group def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[dict]: __lowerCamelCase : Optional[Any] = _number_of_shards_in_gen_kwargs(lowerCamelCase__ ) if num_shards == 1: return [dict(lowerCamelCase__ )] else: __lowerCamelCase : str = _distribute_shards(num_shards=lowerCamelCase__ , max_num_jobs=lowerCamelCase__ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict: return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , lowerCamelCase__ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> dict: __lowerCamelCase : Tuple = {len(lowerCamelCase__ ) for value in gen_kwargs.values() if isinstance(lowerCamelCase__ , lowerCamelCase__ )} __lowerCamelCase : Optional[int] = {} for size in list_sizes: __lowerCamelCase : int = list(range(lowerCamelCase__ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes __lowerCamelCase : List[str] = dict(lowerCamelCase__ ) for key, value in shuffled_kwargs.items(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : str = [value[i] for i in indices_per_size[len(lowerCamelCase__ )]] return shuffled_kwargs
73
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """transfo-xl-wt103""": """https://huggingface.co/transfo-xl-wt103/resolve/main/config.json""", } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = '''transfo-xl''' _UpperCAmelCase : Union[str, Any] = ['''mems'''] _UpperCAmelCase : List[Any] = { '''n_token''': '''vocab_size''', '''hidden_size''': '''d_model''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_6_7_7_3_5 ,SCREAMING_SNAKE_CASE__ : List[Any]=[2_0_0_0_0, 4_0_0_0_0, 2_0_0_0_0_0] ,SCREAMING_SNAKE_CASE__ : List[Any]=1_0_2_4 ,SCREAMING_SNAKE_CASE__ : Optional[int]=1_0_2_4 ,SCREAMING_SNAKE_CASE__ : int=1_6 ,SCREAMING_SNAKE_CASE__ : List[str]=6_4 ,SCREAMING_SNAKE_CASE__ : Any=4_0_9_6 ,SCREAMING_SNAKE_CASE__ : int=4 ,SCREAMING_SNAKE_CASE__ : List[Any]=False ,SCREAMING_SNAKE_CASE__ : List[str]=1_8 ,SCREAMING_SNAKE_CASE__ : Any=1_6_0_0 ,SCREAMING_SNAKE_CASE__ : List[Any]=1_0_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ,SCREAMING_SNAKE_CASE__ : Tuple=0 ,SCREAMING_SNAKE_CASE__ : str=-1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.0 ,SCREAMING_SNAKE_CASE__ : List[Any]=True ,SCREAMING_SNAKE_CASE__ : Optional[Any]="normal" ,SCREAMING_SNAKE_CASE__ : List[Any]=0.01 ,SCREAMING_SNAKE_CASE__ : Dict=0.01 ,SCREAMING_SNAKE_CASE__ : List[Any]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-5 ,SCREAMING_SNAKE_CASE__ : List[str]=0 ,**SCREAMING_SNAKE_CASE__ : List[Any] ,): __lowerCamelCase : Tuple = vocab_size __lowerCamelCase : Optional[int] = [] self.cutoffs.extend(SCREAMING_SNAKE_CASE__) if proj_share_all_but_first: __lowerCamelCase : List[Any] = [False] + [True] * len(self.cutoffs) else: __lowerCamelCase : str = [False] + [False] * len(self.cutoffs) __lowerCamelCase : str = d_model __lowerCamelCase : Dict = d_embed __lowerCamelCase : Any = d_head __lowerCamelCase : List[Any] = d_inner __lowerCamelCase : Dict = div_val __lowerCamelCase : List[Any] = pre_lnorm __lowerCamelCase : Tuple = n_layer __lowerCamelCase : int = n_head __lowerCamelCase : Optional[int] = mem_len __lowerCamelCase : List[str] = same_length __lowerCamelCase : Any = attn_type __lowerCamelCase : int = clamp_len __lowerCamelCase : str = sample_softmax __lowerCamelCase : List[Any] = adaptive __lowerCamelCase : Tuple = dropout __lowerCamelCase : List[Any] = dropatt __lowerCamelCase : Union[str, Any] = untie_r __lowerCamelCase : Any = init __lowerCamelCase : List[str] = init_range __lowerCamelCase : Optional[int] = proj_init_std __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Any = layer_norm_epsilon super().__init__(eos_token_id=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : List[Any]): # Message copied from Transformer-XL documentation logger.info(F"The model {self.model_type} is one of the few models that has no sequence length limit.") return -1 @max_position_embeddings.setter def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Dict): # Message copied from Transformer-XL documentation raise NotImplementedError( F"The model {self.model_type} is one of the few models that has no sequence length limit.")
73
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
1
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A_ : @staticmethod def lowerCAmelCase ( *SCREAMING_SNAKE_CASE__ : Optional[int] ,**SCREAMING_SNAKE_CASE__ : str): pass @is_pipeline_test @require_vision @require_timm @require_torch class A_ ( unittest.TestCase ): _UpperCAmelCase : str = MODEL_FOR_OBJECT_DETECTION_MAPPING def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): __lowerCamelCase : Optional[int] = ObjectDetectionPipeline(model=SCREAMING_SNAKE_CASE__ ,image_processor=SCREAMING_SNAKE_CASE__) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = object_detector('./tests/fixtures/tests_samples/COCO/000000039769.png' ,threshold=0.0) self.assertGreater(len(SCREAMING_SNAKE_CASE__) ,0) for detected_object in outputs: self.assertEqual( SCREAMING_SNAKE_CASE__ ,{ 'score': ANY(SCREAMING_SNAKE_CASE__), 'label': ANY(SCREAMING_SNAKE_CASE__), 'box': {'xmin': ANY(SCREAMING_SNAKE_CASE__), 'ymin': ANY(SCREAMING_SNAKE_CASE__), 'xmax': ANY(SCREAMING_SNAKE_CASE__), 'ymax': ANY(SCREAMING_SNAKE_CASE__)}, } ,) import datasets __lowerCamelCase : int = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' ,'image' ,split='test') __lowerCamelCase : Optional[int] = [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] __lowerCamelCase : Optional[int] = object_detector(SCREAMING_SNAKE_CASE__ ,threshold=0.0) self.assertEqual(len(SCREAMING_SNAKE_CASE__) ,len(SCREAMING_SNAKE_CASE__)) for outputs in batch_outputs: self.assertGreater(len(SCREAMING_SNAKE_CASE__) ,0) for detected_object in outputs: self.assertEqual( SCREAMING_SNAKE_CASE__ ,{ 'score': ANY(SCREAMING_SNAKE_CASE__), 'label': ANY(SCREAMING_SNAKE_CASE__), 'box': {'xmin': ANY(SCREAMING_SNAKE_CASE__), 'ymin': ANY(SCREAMING_SNAKE_CASE__), 'xmax': ANY(SCREAMING_SNAKE_CASE__), 'ymax': ANY(SCREAMING_SNAKE_CASE__)}, } ,) @require_tf @unittest.skip('Object detection not implemented in TF') def lowerCAmelCase ( self : Optional[int]): pass @require_torch def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : str = 'hf-internal-testing/tiny-detr-mobilenetsv3' __lowerCamelCase : List[str] = AutoModelForObjectDetection.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = ObjectDetectionPipeline(model=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ,threshold=0.0) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 1_5_9, 'ymin': 1_2_0, 'xmax': 4_8_0, 'ymax': 3_5_9}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 1_5_9, 'ymin': 1_2_0, 'xmax': 4_8_0, 'ymax': 3_5_9}}, ] ,) __lowerCamelCase : Optional[Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ,threshold=0.0 ,) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 1_5_9, 'ymin': 1_2_0, 'xmax': 4_8_0, 'ymax': 3_5_9}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 1_5_9, 'ymin': 1_2_0, 'xmax': 4_8_0, 'ymax': 3_5_9}}, ], [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 1_5_9, 'ymin': 1_2_0, 'xmax': 4_8_0, 'ymax': 3_5_9}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 1_5_9, 'ymin': 1_2_0, 'xmax': 4_8_0, 'ymax': 3_5_9}}, ], ] ,) @require_torch @slow def lowerCAmelCase ( self : Dict): __lowerCamelCase : Any = 'facebook/detr-resnet-50' __lowerCamelCase : Union[str, Any] = AutoModelForObjectDetection.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = ObjectDetectionPipeline(model=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg') self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_0, 'xmax': 1_7_5, 'ymax': 1_1_7}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 3_3_3, 'ymin': 7_2, 'xmax': 3_6_8, 'ymax': 1_8_7}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 6_3_9, 'ymax': 4_7_3}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ] ,) __lowerCamelCase : str = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ]) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_0, 'xmax': 1_7_5, 'ymax': 1_1_7}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 3_3_3, 'ymin': 7_2, 'xmax': 3_6_8, 'ymax': 1_8_7}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 6_3_9, 'ymax': 4_7_3}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_0, 'xmax': 1_7_5, 'ymax': 1_1_7}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 3_3_3, 'ymin': 7_2, 'xmax': 3_6_8, 'ymax': 1_8_7}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 6_3_9, 'ymax': 4_7_3}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ], ] ,) @require_torch @slow def lowerCAmelCase ( self : int): __lowerCamelCase : List[Any] = 'facebook/detr-resnet-50' __lowerCamelCase : Union[str, Any] = pipeline('object-detection' ,model=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg') self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_0, 'xmax': 1_7_5, 'ymax': 1_1_7}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 3_3_3, 'ymin': 7_2, 'xmax': 3_6_8, 'ymax': 1_8_7}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 6_3_9, 'ymax': 4_7_3}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ] ,) __lowerCamelCase : Union[str, Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ]) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_0, 'xmax': 1_7_5, 'ymax': 1_1_7}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 3_3_3, 'ymin': 7_2, 'xmax': 3_6_8, 'ymax': 1_8_7}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 6_3_9, 'ymax': 4_7_3}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_0, 'xmax': 1_7_5, 'ymax': 1_1_7}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 3_3_3, 'ymin': 7_2, 'xmax': 3_6_8, 'ymax': 1_8_7}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 6_3_9, 'ymax': 4_7_3}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ], ] ,) @require_torch @slow def lowerCAmelCase ( self : Tuple): __lowerCamelCase : str = 0.9985 __lowerCamelCase : List[str] = 'facebook/detr-resnet-50' __lowerCamelCase : List[str] = pipeline('object-detection' ,model=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ,threshold=SCREAMING_SNAKE_CASE__) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 1_3, 'ymin': 5_2, 'xmax': 3_1_4, 'ymax': 4_7_0}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 3_4_5, 'ymin': 2_3, 'xmax': 6_4_0, 'ymax': 3_6_8}}, ] ,) @require_torch @require_pytesseract @slow def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Optional[int] = 'Narsil/layoutlmv3-finetuned-funsd' __lowerCamelCase : List[Any] = 0.9993 __lowerCamelCase : Optional[Any] = pipeline('object-detection' ,model=SCREAMING_SNAKE_CASE__ ,threshold=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = object_detector( 'https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png') self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ,decimals=4) ,[ {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 2_9_4, 'ymin': 2_5_4, 'xmax': 3_4_3, 'ymax': 2_6_4}}, {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 2_9_4, 'ymin': 2_5_4, 'xmax': 3_4_3, 'ymax': 2_6_4}}, ] ,)
73
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a ={ """configuration_blenderbot_small""": [ """BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotSmallConfig""", """BlenderbotSmallOnnxConfig""", ], """tokenization_blenderbot_small""": ["""BlenderbotSmallTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""BlenderbotSmallTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotSmallForCausalLM""", """BlenderbotSmallForConditionalGeneration""", """BlenderbotSmallModel""", """BlenderbotSmallPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """TFBlenderbotSmallForConditionalGeneration""", """TFBlenderbotSmallModel""", """TFBlenderbotSmallPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """FlaxBlenderbotSmallForConditionalGeneration""", """FlaxBlenderbotSmallModel""", """FlaxBlenderbotSmallPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
1
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class A_ ( pl.LightningModule ): def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): super().__init__() __lowerCamelCase : Optional[int] = model __lowerCamelCase : Optional[int] = 2 __lowerCamelCase : Optional[int] = nn.Linear(self.model.config.hidden_size ,self.num_labels) def lowerCAmelCase ( self : str): pass def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: # load longformer model from model identifier __lowerCamelCase : List[Any] = LongformerModel.from_pretrained(lowerCamelCase__ ) __lowerCamelCase : Union[str, Any] = LightningModel(lowerCamelCase__ ) __lowerCamelCase : Tuple = torch.load(lowerCamelCase__ , map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model __lowerCamelCase : Union[str, Any] = LongformerForQuestionAnswering.from_pretrained(lowerCamelCase__ ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(lowerCamelCase__ ) print(F"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": a =argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a =parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
1
import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING a =logging.get_logger(__name__) a ={ """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""", # See all DETR models at https://huggingface.co/models?filter=detr } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[int] = '''detr''' _UpperCAmelCase : Optional[Any] = ['''past_key_values'''] _UpperCAmelCase : Dict = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : List[str]=3 ,SCREAMING_SNAKE_CASE__ : Any=1_0_0 ,SCREAMING_SNAKE_CASE__ : Dict=6 ,SCREAMING_SNAKE_CASE__ : Optional[int]=2_0_4_8 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=8 ,SCREAMING_SNAKE_CASE__ : List[str]=6 ,SCREAMING_SNAKE_CASE__ : Dict=2_0_4_8 ,SCREAMING_SNAKE_CASE__ : List[str]=8 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.0 ,SCREAMING_SNAKE_CASE__ : Dict=0.0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=True ,SCREAMING_SNAKE_CASE__ : str="relu" ,SCREAMING_SNAKE_CASE__ : Tuple=2_5_6 ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Tuple=0.0 ,SCREAMING_SNAKE_CASE__ : Tuple=0.0 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.02 ,SCREAMING_SNAKE_CASE__ : List[str]=1.0 ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Optional[int]="sine" ,SCREAMING_SNAKE_CASE__ : List[Any]="resnet50" ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=False ,SCREAMING_SNAKE_CASE__ : List[Any]=1 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : str=2 ,SCREAMING_SNAKE_CASE__ : Tuple=1 ,SCREAMING_SNAKE_CASE__ : str=1 ,SCREAMING_SNAKE_CASE__ : List[str]=5 ,SCREAMING_SNAKE_CASE__ : str=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,**SCREAMING_SNAKE_CASE__ : Union[str, Any] ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.') if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.') __lowerCamelCase : List[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4']) elif isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[Any] = backbone_config.get('model_type') __lowerCamelCase : Optional[int] = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # set timm attributes to None __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = None, None, None __lowerCamelCase : Dict = use_timm_backbone __lowerCamelCase : str = backbone_config __lowerCamelCase : Tuple = num_channels __lowerCamelCase : Tuple = num_queries __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : Union[str, Any] = encoder_ffn_dim __lowerCamelCase : str = encoder_layers __lowerCamelCase : Optional[int] = encoder_attention_heads __lowerCamelCase : int = decoder_ffn_dim __lowerCamelCase : Optional[Any] = decoder_layers __lowerCamelCase : Any = decoder_attention_heads __lowerCamelCase : List[str] = dropout __lowerCamelCase : Union[str, Any] = attention_dropout __lowerCamelCase : Optional[Any] = activation_dropout __lowerCamelCase : List[Any] = activation_function __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : str = encoder_layerdrop __lowerCamelCase : Optional[Any] = decoder_layerdrop __lowerCamelCase : Dict = encoder_layers __lowerCamelCase : Dict = auxiliary_loss __lowerCamelCase : int = position_embedding_type __lowerCamelCase : Optional[Any] = backbone __lowerCamelCase : Union[str, Any] = use_pretrained_backbone __lowerCamelCase : Union[str, Any] = dilation # Hungarian matcher __lowerCamelCase : List[str] = class_cost __lowerCamelCase : Tuple = bbox_cost __lowerCamelCase : Tuple = giou_cost # Loss coefficients __lowerCamelCase : List[Any] = mask_loss_coefficient __lowerCamelCase : str = dice_loss_coefficient __lowerCamelCase : int = bbox_loss_coefficient __lowerCamelCase : List[Any] = giou_loss_coefficient __lowerCamelCase : List[str] = eos_coefficient super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : str): return self.encoder_attention_heads @property def lowerCAmelCase ( self : Union[str, Any]): return self.d_model @classmethod def lowerCAmelCase ( cls : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : List[Any]): return cls(backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : List[str] = copy.deepcopy(self.__dict__) if output["backbone_config"] is not None: __lowerCamelCase : int = self.backbone_config.to_dict() __lowerCamelCase : Tuple = self.__class__.model_type return output class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = version.parse('''1.11''' ) @property def lowerCAmelCase ( self : List[Any]): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ]) @property def lowerCAmelCase ( self : Tuple): return 1E-5 @property def lowerCAmelCase ( self : Optional[int]): return 1_2
73
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
1
from typing import Any class A_ : def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Union[str, Any] = data __lowerCamelCase : int = None class A_ : def __init__( self : List[Any]): __lowerCamelCase : Optional[Any] = None def lowerCAmelCase ( self : Any): __lowerCamelCase : Tuple = self.head while temp is not None: print(temp.data ,end=' ') __lowerCamelCase : Optional[Any] = temp.next print() def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Optional[int] = Node(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.head __lowerCamelCase : Optional[Any] = new_node def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if node_data_a == node_data_a: return else: __lowerCamelCase : Union[str, Any] = self.head while node_a is not None and node_a.data != node_data_a: __lowerCamelCase : Optional[Any] = node_a.next __lowerCamelCase : int = self.head while node_a is not None and node_a.data != node_data_a: __lowerCamelCase : Tuple = node_a.next if node_a is None or node_a is None: return __lowerCamelCase , __lowerCamelCase : str = node_a.data, node_a.data if __name__ == "__main__": a =LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("""After swapping""") ll.print_list()
73
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
1
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> float: if not nums: raise ValueError('List is empty' ) return sum(lowerCamelCase__ ) / len(lowerCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
73
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : str = [0] * len(lowerCamelCase__ ) __lowerCamelCase : Dict = [] __lowerCamelCase : List[Any] = [1] * len(lowerCamelCase__ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCamelCase__ ) ): if indegree[i] == 0: queue.append(lowerCamelCase__ ) while queue: __lowerCamelCase : Union[str, Any] = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __lowerCamelCase : Optional[int] = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCamelCase__ ) print(max(lowerCamelCase__ ) ) # Adjacency list of Graph a ={0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
73
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): 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 ,SCREAMING_SNAKE_CASE__) * ((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(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[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 lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): 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 : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,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
73
1
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class A_ ( SCREAMING_SNAKE_CASE ): def lowerCAmelCase ( self : Dict): __lowerCamelCase : Dict = pa.array(TypedSequence([1, 2, 3])) self.assertEqual(arr.type ,pa.intaa()) def lowerCAmelCase ( self : Any): with self.assertRaises(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[str] = pa.array(TypedSequence([1, 2, 3]) ,type=pa.intaa()) def lowerCAmelCase ( self : Tuple): with self.assertRaises(SCREAMING_SNAKE_CASE__): __lowerCamelCase : Dict = pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool') ,type=Value('int64'))) def lowerCAmelCase ( self : Any): __lowerCamelCase : int = pa.array(TypedSequence([1, 2, 3] ,type=Value('int32'))) self.assertEqual(arr.type ,pa.intaa()) def lowerCAmelCase ( self : List[str]): with self.assertRaises((TypeError, pa.lib.ArrowInvalid)): __lowerCamelCase : List[Any] = pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64'))) def lowerCAmelCase ( self : Any): __lowerCamelCase : int = pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32'))) self.assertEqual(arr.type ,pa.intaa()) def lowerCAmelCase ( self : str): __lowerCamelCase : str = pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64'))) self.assertEqual(arr.type ,pa.string()) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64'))) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64')) def lowerCAmelCase ( self : str): with self.assertRaises((TypeError, pa.lib.ArrowInvalid)): __lowerCamelCase : List[str] = pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64'))) def lowerCAmelCase ( self : Tuple): __lowerCamelCase : int = pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64'))) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64')) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Dict = pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64'))) self.assertEqual(arr.type ,pa.string()) @require_pil def lowerCAmelCase ( self : Tuple): import PIL.Image __lowerCamelCase : List[str] = PIL.Image.fromarray(np.arange(1_0 ,dtype=np.uinta).reshape(2 ,5)) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=SCREAMING_SNAKE_CASE__) as mock_cast_to_python_objects: __lowerCamelCase : Optional[Any] = pa.array(TypedSequence([{'path': None, 'bytes': b'image_bytes'}, pil_image] ,type=Image())) __lowerCamelCase , __lowerCamelCase : Any = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,SCREAMING_SNAKE_CASE__) self.assertFalse(kwargs['optimize_list_casting']) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: __lowerCamelCase : List[Any] = pa.BufferReader(lowerCamelCase__ ) if isinstance(lowerCamelCase__ , pa.Buffer ) else pa.memory_map(lowerCamelCase__ ) __lowerCamelCase : List[str] = pa.ipc.open_stream(lowerCamelCase__ ) __lowerCamelCase : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : int = pa.BufferOutputStream() __lowerCamelCase : Union[str, Any] = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) __lowerCamelCase , __lowerCamelCase : str = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: __lowerCamelCase : List[str] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def SCREAMING_SNAKE_CASE__ ( ) -> Dict: __lowerCamelCase : str = pa.BufferOutputStream() __lowerCamelCase : Dict = Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCamelCase__ , features=lowerCamelCase__ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) __lowerCamelCase , __lowerCamelCase : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata __lowerCamelCase : Tuple = pa.BufferReader(output.getvalue() ) __lowerCamelCase : Optional[Any] = pa.ipc.open_stream(lowerCamelCase__ ) __lowerCamelCase : pa.Table = f.read_all() __lowerCamelCase : List[Any] = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCamelCase__ ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Any = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ , hash_salt='split_name' , check_duplicates=lowerCamelCase__ , ) as writer: with pytest.raises(lowerCamelCase__ ): writer.write({'col_1': 'foo', 'col_2': 1} , key=[1, 2] ) __lowerCamelCase , __lowerCamelCase : int = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 1_0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[int] = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ , hash_salt='split_name' , check_duplicates=lowerCamelCase__ , ) as writer: with pytest.raises(lowerCamelCase__ ): writer.write({'col_1': 'foo', 'col_2': 1} , key=1_0 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=1_0 ) __lowerCamelCase , __lowerCamelCase : str = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 1_0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: __lowerCamelCase : str = pa.BufferOutputStream() with ArrowWriter( stream=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ , hash_salt='split_name' , check_duplicates=lowerCamelCase__ , ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} , key=1 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=2 ) __lowerCamelCase , __lowerCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : Any = pa.BufferOutputStream() __lowerCamelCase : Dict = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: __lowerCamelCase : str = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : int = pa.BufferOutputStream() __lowerCamelCase : Dict = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) __lowerCamelCase , __lowerCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: __lowerCamelCase : Union[str, Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : Dict = pa.BufferOutputStream() __lowerCamelCase : Any = pa.schema(lowerCamelCase__ ) if fields else None with ArrowWriter(stream=lowerCamelCase__ , schema=lowerCamelCase__ , writer_batch_size=lowerCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) __lowerCamelCase , __lowerCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: __lowerCamelCase : List[str] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def SCREAMING_SNAKE_CASE__ ( ) -> Optional[int]: with tempfile.TemporaryDirectory() as tmp_dir: __lowerCamelCase : str = {'col_1': pa.string(), 'col_2': pa.intaa()} __lowerCamelCase : Optional[int] = os.path.join(lowerCamelCase__ , 'test.arrow' ) with ArrowWriter(path=lowerCamelCase__ , schema=pa.schema(lowerCamelCase__ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) __lowerCamelCase , __lowerCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCamelCase__ , metadata=writer._schema.metadata ) _check_output(lowerCamelCase__ , 1 ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if pa.types.is_list(lowerCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: if isinstance(lst[0] , lowerCamelCase__ ): change_first_primitive_element_in_list(lst[0] , lowerCamelCase__ ) else: __lowerCamelCase : List[str] = value @pytest.mark.parametrize('optimized_int_type, expected_dtype' , [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Any = pa.array(TypedSequence(lowerCamelCase__ , optimized_int_type=lowerCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype' , [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ] , ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: # in range __lowerCamelCase : Any = pa.array(OptimizedTypedSequence(lowerCamelCase__ , col=lowerCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications __lowerCamelCase : List[str] = copy.deepcopy(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : str = pa.array(OptimizedTypedSequence(lowerCamelCase__ , col=lowerCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception' , [False, True] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: __lowerCamelCase : List[str] = str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[int]: __lowerCamelCase : Optional[int] = 'mock://dataset-train.arrow' with ArrowWriter(path=lowerCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(lowerCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) __lowerCamelCase , __lowerCamelCase : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ) -> Optional[Any]: __lowerCamelCase : Optional[Any] = pa.BufferOutputStream() with ParquetWriter(stream=lowerCamelCase__ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) __lowerCamelCase , __lowerCamelCase : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 __lowerCamelCase : Tuple = pa.BufferReader(output.getvalue() ) __lowerCamelCase : pa.Table = pq.read_table(lowerCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files' , [False, True] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: import PIL.Image __lowerCamelCase : Dict = str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(lowerCamelCase__ , format='png' ) __lowerCamelCase : Union[str, Any] = pa.BufferOutputStream() with ParquetWriter( stream=lowerCamelCase__ , features=Features({'image': Image()} ) , embed_local_files=lowerCamelCase__ ) as writer: writer.write({'image': image_path} ) writer.finalize() __lowerCamelCase : Dict = pa.BufferReader(output.getvalue() ) __lowerCamelCase : pa.Table = pq.read_table(lowerCamelCase__ ) __lowerCamelCase : Any = pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'] , lowerCamelCase__ ) with open(lowerCamelCase__ , 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def SCREAMING_SNAKE_CASE__ ( ) -> Optional[Any]: __lowerCamelCase : List[str] = pa.schema([pa.field('col_1' , pa.string() , nullable=lowerCamelCase__ )] ) __lowerCamelCase : List[str] = pa.BufferOutputStream() with ArrowWriter(stream=lowerCamelCase__ ) as writer: writer._build_writer(inferred_schema=lowerCamelCase__ ) assert writer._schema == pa.schema([pa.field('col_1' , pa.string() )] )
73
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
1
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Tuple = tmp_path / 'file.csv' __lowerCamelCase : Optional[int] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(lowerCamelCase__ , 'w' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : List[Any] = tmp_path / 'malformed_file.csv' __lowerCamelCase : Optional[int] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(lowerCamelCase__ , 'w' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict: __lowerCamelCase : Tuple = tmp_path / 'csv_with_image.csv' __lowerCamelCase : Union[str, Any] = textwrap.dedent( F"\\n image\n {image_file}\n " ) with open(lowerCamelCase__ , 'w' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Optional[int] = tmp_path / 'csv_with_label.csv' __lowerCamelCase : Tuple = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(lowerCamelCase__ , 'w' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[int] = tmp_path / 'csv_with_int_list.csv' __lowerCamelCase : Optional[Any] = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(lowerCamelCase__ , 'w' ) as f: f.write(lowerCamelCase__ ) return str(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: __lowerCamelCase : str = Csv() __lowerCamelCase : Union[str, Any] = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(lowerCamelCase__ , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(lowerCamelCase__ ) in record.message for record in caplog.records ) @require_pil def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: with open(lowerCamelCase__ , encoding='utf-8' ) as f: __lowerCamelCase : List[Any] = f.read().splitlines()[1] __lowerCamelCase : str = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) __lowerCamelCase : int = csv._generate_tables([[csv_file_with_image]] ) __lowerCamelCase : Optional[int] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() __lowerCamelCase : Union[str, Any] = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: with open(lowerCamelCase__ , encoding='utf-8' ) as f: __lowerCamelCase : Dict = f.read().splitlines()[1:] __lowerCamelCase : Any = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) __lowerCamelCase : List[Any] = csv._generate_tables([[csv_file_with_label]] ) __lowerCamelCase : Tuple = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() __lowerCamelCase : str = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(lowerCamelCase__ ) for label in labels] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: __lowerCamelCase : Union[str, Any] = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda lowerCamelCase__ : [int(lowerCamelCase__ ) for i in x.split()]} ) __lowerCamelCase : Dict = csv._generate_tables([[csv_file_with_int_list]] ) __lowerCamelCase : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) __lowerCamelCase : List[str] = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
73
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
1
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
1
import unittest from transformers import DonutProcessor a ="""naver-clova-ix/donut-base""" class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : str): __lowerCamelCase : Tuple = DonutProcessor.from_pretrained(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : str = { 'name': 'John Doe', 'age': '99', 'city': 'Atlanta', 'state': 'GA', 'zip': '30301', 'phone': '123-4567', 'nicknames': [{'nickname': 'Johnny'}, {'nickname': 'JD'}], } __lowerCamelCase : List[Any] = ( '<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>' '<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>' '<s_nicknames><s_nickname>Johnny</s_nickname>' '<sep/><s_nickname>JD</s_nickname></s_nicknames>' ) __lowerCamelCase : Tuple = self.processor.tokenajson(SCREAMING_SNAKE_CASE__) self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
73
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) a ={ """configuration_layoutlmv2""": ["""LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMv2Config"""], """processing_layoutlmv2""": ["""LayoutLMv2Processor"""], """tokenization_layoutlmv2""": ["""LayoutLMv2Tokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""LayoutLMv2TokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""LayoutLMv2FeatureExtractor"""] a =["""LayoutLMv2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """LayoutLMv2ForQuestionAnswering""", """LayoutLMv2ForSequenceClassification""", """LayoutLMv2ForTokenClassification""", """LayoutLMv2Layer""", """LayoutLMv2Model""", """LayoutLMv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
1
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=False ) -> Optional[int]: try: __lowerCamelCase : int = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __lowerCamelCase : List[Any] = default else: # KEY is set, convert it to True or False. try: __lowerCamelCase : Any = strtobool(lowerCamelCase__ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"If set, {key} must be yes or no." ) return _value a =parse_flag_from_env("""RUN_SLOW""", default=False) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: return unittest.skip('Test was skipped' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: return unittest.skipUnless(_run_slow_tests , 'test is slow' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: return unittest.skipUnless(not torch.cuda.is_available() , 'test requires only a CPU' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[int]: return unittest.skipUnless(torch.cuda.is_available() , 'test requires a GPU' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: return unittest.skipUnless(is_xpu_available() , 'test requires a XPU' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: return unittest.skipUnless(is_mps_available() , 'test requires a `mps` backend support in `torch`' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[int]: return unittest.skipUnless( is_transformers_available() and is_datasets_available() , 'test requires the Hugging Face suite' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: return unittest.skipUnless(is_bnb_available() , 'test requires the bitsandbytes library' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: return unittest.skipUnless(is_tpu_available() , 'test requires TPU' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Union[str, Any]: return unittest.skipUnless(torch.cuda.device_count() == 1 , 'test requires a GPU' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return unittest.skipUnless(torch.xpu.device_count() == 1 , 'test requires a XPU' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: return unittest.skipUnless(torch.cuda.device_count() > 1 , 'test requires multiple GPUs' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: return unittest.skipUnless(torch.xpu.device_count() > 1 , 'test requires multiple XPUs' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[int]: return unittest.skipUnless(is_safetensors_available() , 'test requires safetensors' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return unittest.skipUnless(is_deepspeed_available() , 'test requires DeepSpeed' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: return unittest.skipUnless(is_torch_version('>=' , '1.12.0' ) , 'test requires torch version >= 1.12.0' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__=None , lowerCamelCase__=None ) -> Any: if test_case is None: return partial(lowerCamelCase__ , version=lowerCamelCase__ ) return unittest.skipUnless(is_torch_version('>=' , lowerCamelCase__ ) , F"test requires torch version >= {version}" )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: return unittest.skipUnless(is_tensorboard_available() , 'test requires Tensorboard' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: return unittest.skipUnless(is_wandb_available() , 'test requires wandb' )(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: return unittest.skipUnless(is_comet_ml_available() , 'test requires comet_ml' )(lowerCamelCase__ ) a =( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: return unittest.skipUnless( _atleast_one_tracker_available , 'test requires at least one tracker to be available and for `comet_ml` to not be installed' , )(lowerCamelCase__ ) class A_ ( unittest.TestCase ): _UpperCAmelCase : Union[str, Any] = True @classmethod def lowerCAmelCase ( cls : int): __lowerCamelCase : List[Any] = tempfile.mkdtemp() @classmethod def lowerCAmelCase ( cls : int): if os.path.exists(cls.tmpdir): shutil.rmtree(cls.tmpdir) def lowerCAmelCase ( self : Any): if self.clear_on_setup: for path in Path(self.tmpdir).glob('**/*'): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(SCREAMING_SNAKE_CASE__) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[Any]): super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[mock.Mock, List[mock.Mock]]): __lowerCamelCase : Tuple = mocks if isinstance(SCREAMING_SNAKE_CASE__ ,(tuple, list)) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Dict: __lowerCamelCase : int = AcceleratorState() __lowerCamelCase : Optional[int] = tensor[None].clone().to(state.device ) __lowerCamelCase : Dict = gather(lowerCamelCase__ ).cpu() __lowerCamelCase : Union[str, Any] = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , lowerCamelCase__ ): return False return True class A_ : def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Union[str, Any] = returncode __lowerCamelCase : List[str] = stdout __lowerCamelCase : Tuple = stderr async def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: while True: __lowerCamelCase : str = await stream.readline() if line: callback(lowerCamelCase__ ) else: break async def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=False , lowerCamelCase__=False ) -> _RunOutput: if echo: print('\nRunning: ' , ' '.join(lowerCamelCase__ ) ) __lowerCamelCase : str = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowerCamelCase__ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCamelCase__ , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __lowerCamelCase : int = [] __lowerCamelCase : str = [] def tee(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="" ): __lowerCamelCase : Any = line.decode('utf-8' ).rstrip() sink.append(lowerCamelCase__ ) if not quiet: print(lowerCamelCase__ , lowerCamelCase__ , file=lowerCamelCase__ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda lowerCamelCase__ : tee(lowerCamelCase__ , lowerCamelCase__ , sys.stdout , label='stdout:' ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda lowerCamelCase__ : tee(lowerCamelCase__ , lowerCamelCase__ , sys.stderr , label='stderr:' ) ) ), ] , timeout=lowerCamelCase__ , ) return _RunOutput(await p.wait() , lowerCamelCase__ , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=1_8_0 , lowerCamelCase__=False , lowerCamelCase__=True ) -> _RunOutput: __lowerCamelCase : Union[str, Any] = asyncio.get_event_loop() __lowerCamelCase : str = loop.run_until_complete( _stream_subprocess(lowerCamelCase__ , env=lowerCamelCase__ , stdin=lowerCamelCase__ , timeout=lowerCamelCase__ , quiet=lowerCamelCase__ , echo=lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = ' '.join(lowerCamelCase__ ) if result.returncode > 0: __lowerCamelCase : Optional[int] = '\n'.join(result.stderr ) raise RuntimeError( F"'{cmd_str}' failed with returncode {result.returncode}\n\n" F"The combined stderr from workers follows:\n{stderr}" ) return result class A_ ( SCREAMING_SNAKE_CASE ): pass def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=False ) -> int: try: __lowerCamelCase : List[str] = subprocess.check_output(lowerCamelCase__ , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(lowerCamelCase__ , 'decode' ): __lowerCamelCase : str = output.decode('utf-8' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F"Command `{' '.join(lowerCamelCase__ )}` failed with the following error:\n\n{e.output.decode()}" ) from e
73
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 A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
1
from math import sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1_0_0_0_1 ) -> int: __lowerCamelCase : List[Any] = 0 __lowerCamelCase : str = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCamelCase__ ): count += 1 while count != nth: number += 2 if is_prime(lowerCamelCase__ ): count += 1 return number if __name__ == "__main__": print(F"""{solution() = }""")
73
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> list[int]: __lowerCamelCase : str = len(lowerCamelCase__ ) for i in range(lowerCamelCase__ ): for j in range(i + 1 , lowerCamelCase__ ): if numbers[j] < numbers[i]: __lowerCamelCase , __lowerCamelCase : str = numbers[j], numbers[i] return numbers if __name__ == "__main__": a =input("""Enter numbers separated by a comma:\n""").strip() a =[int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
73
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[str]: class A_ : def __init__( self : Dict ,SCREAMING_SNAKE_CASE__ : Any): __lowerCamelCase : Union[str, Any] = metric_id class A_ : _UpperCAmelCase : Optional[Any] = [MetricMock(SCREAMING_SNAKE_CASE ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def lowerCAmelCase ( self : Dict): return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock() ) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: if "tmp_path" in args: __lowerCamelCase : Any = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args ) with pytest.warns(lowerCamelCase__ , match='https://huggingface.co/docs/evaluate' ): func(*lowerCamelCase__ )
73
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
1
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[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 lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
1
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: # Load checkpoint __lowerCamelCase : Union[str, Any] = torch.load(lowerCamelCase__ , map_location='cpu' ) __lowerCamelCase : Dict = chkpt['model'] # We have the base model one level deeper than the original XLM repository __lowerCamelCase : Any = {} for k, v in state_dict.items(): if "pred_layer" in k: __lowerCamelCase : int = v else: __lowerCamelCase : List[Any] = v __lowerCamelCase : Any = chkpt['params'] __lowerCamelCase : List[Any] = {n: v for n, v in config.items() if not isinstance(lowerCamelCase__ , (torch.FloatTensor, numpy.ndarray) )} __lowerCamelCase : Union[str, Any] = chkpt['dico_word2id'] __lowerCamelCase : Union[str, Any] = {s + '</w>' if s.find('@@' ) == -1 and i > 1_3 else s.replace('@@' , '' ): i for s, i in vocab.items()} # Save pytorch-model __lowerCamelCase : Tuple = pytorch_dump_folder_path + '/' + WEIGHTS_NAME __lowerCamelCase : List[Any] = pytorch_dump_folder_path + '/' + CONFIG_NAME __lowerCamelCase : List[str] = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['vocab_file'] print(F"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(lowerCamelCase__ , lowerCamelCase__ ) print(F"Save configuration file to {pytorch_config_dump_path}" ) with open(lowerCamelCase__ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(lowerCamelCase__ , indent=2 ) + '\n' ) print(F"Save vocab file to {pytorch_config_dump_path}" ) with open(lowerCamelCase__ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(lowerCamelCase__ , indent=2 ) + '\n' ) if __name__ == "__main__": a =argparse.ArgumentParser() # Required parameters parser.add_argument( """--xlm_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a =parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
1
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class A_ : def __init__( self : Optional[Any]): __lowerCamelCase : Dict = '' __lowerCamelCase : str = '' __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : str = 0 __lowerCamelCase : Any = 2_5_6 __lowerCamelCase : Tuple = 0 __lowerCamelCase : Any = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : str = 0 def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Optional[Any] = cva.imread(SCREAMING_SNAKE_CASE__ ,0) __lowerCamelCase : Optional[int] = copy.deepcopy(self.img) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = plt.hist(self.img.ravel() ,2_5_6 ,[0, 2_5_6] ,label='x') __lowerCamelCase : str = np.sum(SCREAMING_SNAKE_CASE__) for i in range(len(SCREAMING_SNAKE_CASE__)): __lowerCamelCase : List[str] = x[i] / self.k self.sk += prk __lowerCamelCase : List[str] = (self.L - 1) * self.sk if self.rem != 0: __lowerCamelCase : Union[str, Any] = int(last % last) __lowerCamelCase : Optional[int] = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = int(np.ma.count(self.img) / self.img[1].size) __lowerCamelCase : Dict = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): __lowerCamelCase : Optional[int] = self.img[j][i] if num != self.last_list[num]: __lowerCamelCase : Optional[Any] = self.last_list[num] cva.imwrite('output_data/output.jpg' ,self.img) def lowerCAmelCase ( self : int): plt.hist(self.img.ravel() ,2_5_6 ,[0, 2_5_6]) def lowerCAmelCase ( self : List[Any]): cva.imshow('Output-Image' ,self.img) cva.imshow('Input-Image' ,self.original_image) cva.waitKey(5_0_0_0) cva.destroyAllWindows() if __name__ == "__main__": a =os.path.join(os.path.basename(__file__), """image_data/input.jpg""") a =ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
73
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
1
from math import isqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> bool: return all(number % divisor != 0 for divisor in range(2 , isqrt(lowerCamelCase__ ) + 1 ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1_0**6 ) -> int: __lowerCamelCase : List[str] = 0 __lowerCamelCase : List[str] = 1 __lowerCamelCase : Optional[int] = 7 while prime_candidate < max_prime: primes_count += is_prime(lowerCamelCase__ ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"""{solution() = }""")
73
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
1
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
1
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 a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = ['''audio_values''', '''audio_mask'''] def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : str=2_0_4_8 ,SCREAMING_SNAKE_CASE__ : Dict=1 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=[1_6, 1_6] ,SCREAMING_SNAKE_CASE__ : Dict=1_2_8 ,SCREAMING_SNAKE_CASE__ : str=4_4_1_0_0 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=8_6 ,SCREAMING_SNAKE_CASE__ : Tuple=2_0_4_8 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 ,**SCREAMING_SNAKE_CASE__ : Any ,): super().__init__( feature_size=SCREAMING_SNAKE_CASE__ ,sampling_rate=SCREAMING_SNAKE_CASE__ ,padding_value=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : int = spectrogram_length __lowerCamelCase : Tuple = num_channels __lowerCamelCase : int = patch_size __lowerCamelCase : Any = feature_size // self.patch_size[1] __lowerCamelCase : Tuple = n_fft __lowerCamelCase : List[str] = sampling_rate // hop_length_to_sampling_rate __lowerCamelCase : Tuple = sampling_rate __lowerCamelCase : str = padding_value __lowerCamelCase : Tuple = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 ,num_mel_filters=SCREAMING_SNAKE_CASE__ ,min_frequency=0.0 ,max_frequency=22050.0 ,sampling_rate=SCREAMING_SNAKE_CASE__ ,norm='slaney' ,mel_scale='slaney' ,).T def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : np.array): __lowerCamelCase : Dict = spectrogram( SCREAMING_SNAKE_CASE__ ,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 : Optional[Any] = log_spec[:, :-1] __lowerCamelCase : List[Any] = log_spec - 20.0 __lowerCamelCase : Tuple = np.clip(log_spec / 40.0 ,-2.0 ,0.0) + 1.0 return log_spec def __call__( self : List[str] ,SCREAMING_SNAKE_CASE__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = True ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,**SCREAMING_SNAKE_CASE__ : int ,): 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 : int = isinstance(SCREAMING_SNAKE_CASE__ ,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 : Tuple = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE__ ,(list, tuple)) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list))) ) if is_batched: __lowerCamelCase : int = [np.asarray([speech] ,dtype=np.floataa).T for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE__ ,np.ndarray): __lowerCamelCase : Optional[Any] = np.asarray(SCREAMING_SNAKE_CASE__ ,dtype=np.floataa) elif isinstance(SCREAMING_SNAKE_CASE__ ,np.ndarray) and raw_speech.dtype is np.dtype(np.floataa): __lowerCamelCase : Optional[int] = raw_speech.astype(np.floataa) # always return batch if not is_batched: __lowerCamelCase : int = [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] ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Any = [np.asarray(SCREAMING_SNAKE_CASE__ ,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 : Dict = [ (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 : int = np.array(SCREAMING_SNAKE_CASE__).astype(np.floataa) # convert into correct format for padding __lowerCamelCase : Any = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch __lowerCamelCase : List[str] = np.ones([len(SCREAMING_SNAKE_CASE__), 1, max_time_len, self.feature_size]).astype(np.floataa) __lowerCamelCase : Any = padded_audio_features * self.padding_value for i in range(len(SCREAMING_SNAKE_CASE__)): __lowerCamelCase : int = audio_features[i] __lowerCamelCase : Union[str, Any] = feature # return as BatchFeature if return_attention_mask: __lowerCamelCase : int = {'audio_values': padded_audio_features, 'audio_mask': audio_mask} else: __lowerCamelCase : List[str] = {'audio_values': padded_audio_features} __lowerCamelCase : List[str] = BatchFeature(data=SCREAMING_SNAKE_CASE__ ,tensor_type=SCREAMING_SNAKE_CASE__) return encoded_inputs
73
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
1
import math from numpy import inf from scipy.integrate import quad def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> float: if num <= 0: raise ValueError('math domain error' ) return quad(lowerCamelCase__ , 0 , lowerCamelCase__ , args=(lowerCamelCase__) )[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: return math.pow(lowerCamelCase__ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a =logging.get_logger(__name__) a ={ """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = '''dpr''' def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple=3_0_5_2_2 ,SCREAMING_SNAKE_CASE__ : Any=7_6_8 ,SCREAMING_SNAKE_CASE__ : str=1_2 ,SCREAMING_SNAKE_CASE__ : Tuple=1_2 ,SCREAMING_SNAKE_CASE__ : Any=3_0_7_2 ,SCREAMING_SNAKE_CASE__ : Dict="gelu" ,SCREAMING_SNAKE_CASE__ : Tuple=0.1 ,SCREAMING_SNAKE_CASE__ : str=0.1 ,SCREAMING_SNAKE_CASE__ : int=5_1_2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=1E-12 ,SCREAMING_SNAKE_CASE__ : Dict=0 ,SCREAMING_SNAKE_CASE__ : List[Any]="absolute" ,SCREAMING_SNAKE_CASE__ : int = 0 ,**SCREAMING_SNAKE_CASE__ : Dict ,): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = vocab_size __lowerCamelCase : Optional[int] = hidden_size __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : Dict = hidden_act __lowerCamelCase : str = intermediate_size __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : Tuple = attention_probs_dropout_prob __lowerCamelCase : Tuple = max_position_embeddings __lowerCamelCase : int = type_vocab_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : List[str] = layer_norm_eps __lowerCamelCase : Any = projection_dim __lowerCamelCase : Union[str, Any] = position_embedding_type
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
1
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : UNetaDModel ,SCREAMING_SNAKE_CASE__ : UNetaDModel ,SCREAMING_SNAKE_CASE__ : DDPMScheduler ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,): super().__init__() __lowerCamelCase : str = value_function __lowerCamelCase : List[Any] = unet __lowerCamelCase : str = scheduler __lowerCamelCase : List[Any] = env __lowerCamelCase : List[Any] = env.get_dataset() __lowerCamelCase : Union[str, Any] = {} for key in self.data.keys(): try: __lowerCamelCase : Union[str, Any] = self.data[key].mean() except: # noqa: E722 pass __lowerCamelCase : Tuple = {} for key in self.data.keys(): try: __lowerCamelCase : int = self.data[key].std() except: # noqa: E722 pass __lowerCamelCase : Tuple = env.observation_space.shape[0] __lowerCamelCase : Dict = env.action_space.shape[0] def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): return (x_in - self.means[key]) / self.stds[key] def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict): return x_in * self.stds[key] + self.means[key] def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : List[Any]): if type(SCREAMING_SNAKE_CASE__) is dict: return {k: self.to_torch(SCREAMING_SNAKE_CASE__) for k, v in x_in.items()} elif torch.is_tensor(SCREAMING_SNAKE_CASE__): return x_in.to(self.unet.device) return torch.tensor(SCREAMING_SNAKE_CASE__ ,device=self.unet.device) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : List[str]): for key, val in cond.items(): __lowerCamelCase : str = val.clone() return x_in def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple): __lowerCamelCase : Dict = x.shape[0] __lowerCamelCase : Union[str, Any] = None for i in tqdm.tqdm(self.scheduler.timesteps): # create batch of timesteps to pass into model __lowerCamelCase : List[str] = torch.full((batch_size,) ,SCREAMING_SNAKE_CASE__ ,device=self.unet.device ,dtype=torch.long) for _ in range(SCREAMING_SNAKE_CASE__): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models __lowerCamelCase : Tuple = self.value_function(x.permute(0 ,2 ,1) ,SCREAMING_SNAKE_CASE__).sample __lowerCamelCase : str = torch.autograd.grad([y.sum()] ,[x])[0] __lowerCamelCase : Optional[Any] = self.scheduler._get_variance(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = torch.exp(0.5 * posterior_variance) __lowerCamelCase : List[str] = model_std * grad __lowerCamelCase : str = 0 __lowerCamelCase : Optional[Any] = x.detach() __lowerCamelCase : Optional[Any] = x + scale * grad __lowerCamelCase : Optional[int] = self.reset_xa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.action_dim) __lowerCamelCase : Optional[int] = self.unet(x.permute(0 ,2 ,1) ,SCREAMING_SNAKE_CASE__).sample.permute(0 ,2 ,1) # TODO: verify deprecation of this kwarg __lowerCamelCase : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,predict_epsilon=SCREAMING_SNAKE_CASE__)['prev_sample'] # apply conditions to the trajectory (set the initial state) __lowerCamelCase : Optional[Any] = self.reset_xa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.action_dim) __lowerCamelCase : List[Any] = self.to_torch(SCREAMING_SNAKE_CASE__) return x, y def __call__( self : Any ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : List[Any]=6_4 ,SCREAMING_SNAKE_CASE__ : int=3_2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.1): # normalize the observations and create batch dimension __lowerCamelCase : Tuple = self.normalize(SCREAMING_SNAKE_CASE__ ,'observations') __lowerCamelCase : List[str] = obs[None].repeat(SCREAMING_SNAKE_CASE__ ,axis=0) __lowerCamelCase : Optional[int] = {0: self.to_torch(SCREAMING_SNAKE_CASE__)} __lowerCamelCase : int = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) __lowerCamelCase : Any = randn_tensor(SCREAMING_SNAKE_CASE__ ,device=self.unet.device) __lowerCamelCase : Tuple = self.reset_xa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.action_dim) __lowerCamelCase : List[str] = self.to_torch(SCREAMING_SNAKE_CASE__) # run the diffusion process __lowerCamelCase , __lowerCamelCase : Optional[Any] = self.run_diffusion(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) # sort output trajectories by value __lowerCamelCase : Tuple = y.argsort(0 ,descending=SCREAMING_SNAKE_CASE__).squeeze() __lowerCamelCase : Tuple = x[sorted_idx] __lowerCamelCase : List[str] = sorted_values[:, :, : self.action_dim] __lowerCamelCase : List[Any] = actions.detach().cpu().numpy() __lowerCamelCase : str = self.de_normalize(SCREAMING_SNAKE_CASE__ ,key='actions') # select the action with the highest value if y is not None: __lowerCamelCase : Any = 0 else: # if we didn't run value guiding, select a random action __lowerCamelCase : Dict = np.random.randint(0 ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = denorm_actions[selected_index, 0] return denorm_actions
73
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
1
import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: __lowerCamelCase : Tuple = 1.5 __lowerCamelCase : List[Any] = int(factor * num_class_images ) __lowerCamelCase : Optional[int] = ClipClient( url='https://knn.laion.ai/knn-service' , indice_name='laion_400m' , num_images=lowerCamelCase__ , aesthetic_weight=0.1 ) os.makedirs(F"{class_data_dir}/images" , exist_ok=lowerCamelCase__ ) if len(list(Path(F"{class_data_dir}/images" ).iterdir() ) ) >= num_class_images: return while True: __lowerCamelCase : Optional[Any] = client.query(text=lowerCamelCase__ ) if len(lowerCamelCase__ ) >= factor * num_class_images or num_images > 1e4: break else: __lowerCamelCase : str = int(factor * num_images ) __lowerCamelCase : Tuple = ClipClient( url='https://knn.laion.ai/knn-service' , indice_name='laion_400m' , num_images=lowerCamelCase__ , aesthetic_weight=0.1 , ) __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Tuple = 0 __lowerCamelCase : Any = tqdm(desc='downloading real regularization images' , total=lowerCamelCase__ ) with open(F"{class_data_dir}/caption.txt" , 'w' ) as fa, open(F"{class_data_dir}/urls.txt" , 'w' ) as fa, open( F"{class_data_dir}/images.txt" , 'w' ) as fa: while total < num_class_images: __lowerCamelCase : List[Any] = class_images[count] count += 1 try: __lowerCamelCase : Optional[Any] = requests.get(images['url'] ) if img.status_code == 2_0_0: __lowerCamelCase : Dict = Image.open(BytesIO(img.content ) ) with open(F"{class_data_dir}/images/{total}.jpg" , 'wb' ) as f: f.write(img.content ) fa.write(images['caption'] + '\n' ) fa.write(images['url'] + '\n' ) fa.write(F"{class_data_dir}/images/{total}.jpg" + '\n' ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def SCREAMING_SNAKE_CASE__ ( ) -> Optional[int]: __lowerCamelCase : Optional[int] = argparse.ArgumentParser('' , add_help=lowerCamelCase__ ) parser.add_argument('--class_prompt' , help='text prompt to retrieve images' , required=lowerCamelCase__ , type=lowerCamelCase__ ) parser.add_argument('--class_data_dir' , help='path to save images' , required=lowerCamelCase__ , type=lowerCamelCase__ ) parser.add_argument('--num_class_images' , help='number of images to download' , default=2_0_0 , type=lowerCamelCase__ ) return parser.parse_args() if __name__ == "__main__": a =parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
73
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
1
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = prime_factors(lowerCamelCase__ ) if is_square_free(lowerCamelCase__ ): return -1 if len(lowerCamelCase__ ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
73
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
1
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__="" ) -> str: __lowerCamelCase : str = tempfile.mkdtemp() return os.path.join(lowerCamelCase__ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : int = torch.rand(1_2 ,dtype=torch.floataa) - 0.5 __lowerCamelCase : Dict = AgentAudio(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = str(agent_type.to_string()) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ ,agent_type.to_raw() ,atol=1E-4)) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__)) # Ensure that the file contains the same value as the original tensor __lowerCamelCase , __lowerCamelCase : Optional[Any] = sf.read(SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ ,torch.tensor(SCREAMING_SNAKE_CASE__) ,atol=1E-4)) def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = torch.rand(1_2 ,dtype=torch.floataa) - 0.5 __lowerCamelCase : Optional[Any] = get_new_path(suffix='.wav') sf.write(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,1_6_0_0_0) __lowerCamelCase : Optional[Any] = AgentAudio(SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ ,agent_type.to_raw() ,atol=1E-4)) self.assertEqual(agent_type.to_string() ,SCREAMING_SNAKE_CASE__) @require_vision @require_torch class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Union[str, Any] = torch.randint(0 ,2_5_6 ,(6_4, 6_4, 3)) __lowerCamelCase : Any = AgentImage(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = str(agent_type.to_string()) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ ,agent_type._tensor ,atol=1E-4)) self.assertIsInstance(agent_type.to_raw() ,Image.Image) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__)) def lowerCAmelCase ( self : Any): __lowerCamelCase : Dict = Path(get_tests_dir('fixtures/tests_samples/COCO')) / '000000039769.png' __lowerCamelCase : Optional[Any] = Image.open(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = AgentImage(SCREAMING_SNAKE_CASE__) self.assertTrue(path.samefile(agent_type.to_string())) self.assertTrue(image == agent_type.to_raw()) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__)) def lowerCAmelCase ( self : Any): __lowerCamelCase : int = Path(get_tests_dir('fixtures/tests_samples/COCO')) / '000000039769.png' __lowerCamelCase : List[Any] = Image.open(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = AgentImage(SCREAMING_SNAKE_CASE__) self.assertFalse(path.samefile(agent_type.to_string())) self.assertTrue(image == agent_type.to_raw()) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__)) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : str): __lowerCamelCase : Any = 'Hey!' __lowerCamelCase : List[str] = AgentText(SCREAMING_SNAKE_CASE__) self.assertEqual(SCREAMING_SNAKE_CASE__ ,agent_type.to_string()) self.assertEqual(SCREAMING_SNAKE_CASE__ ,agent_type.to_raw()) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
73
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
1
import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: return x + 2 class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : int): __lowerCamelCase : Any = 'x = 3' __lowerCamelCase : Tuple = {} __lowerCamelCase : Union[str, Any] = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) assert result == 3 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3}) __lowerCamelCase : List[Any] = 'x = y' __lowerCamelCase : str = {'y': 5} __lowerCamelCase : Dict = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 5, 'y': 5}) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = 'y = add_two(x)' __lowerCamelCase : Optional[Any] = {'x': 3} __lowerCamelCase : Dict = evaluate(SCREAMING_SNAKE_CASE__ ,{'add_two': add_two} ,state=SCREAMING_SNAKE_CASE__) assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'y': 5}) # Won't work without the tool with CaptureStdout() as out: __lowerCamelCase : str = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) assert result is None assert "tried to execute add_two" in out.out def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = 'x = 3' __lowerCamelCase : Tuple = {} __lowerCamelCase : Optional[int] = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) assert result == 3 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3}) def lowerCAmelCase ( self : Any): __lowerCamelCase : Any = 'test_dict = {\'x\': x, \'y\': add_two(x)}' __lowerCamelCase : Dict = {'x': 3} __lowerCamelCase : Optional[int] = evaluate(SCREAMING_SNAKE_CASE__ ,{'add_two': add_two} ,state=SCREAMING_SNAKE_CASE__) self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'y': 5}) self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'test_dict': {'x': 3, 'y': 5}}) def lowerCAmelCase ( self : Any): __lowerCamelCase : Union[str, Any] = 'x = 3\ny = 5' __lowerCamelCase : Optional[int] = {} __lowerCamelCase : List[Any] = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'y': 5}) def lowerCAmelCase ( self : str): __lowerCamelCase : int = 'text = f\'This is x: {x}.\'' __lowerCamelCase : Optional[int] = {'x': 3} __lowerCamelCase : str = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'text': 'This is x: 3.'}) def lowerCAmelCase ( self : Dict): __lowerCamelCase : Any = 'if x <= 3:\n y = 2\nelse:\n y = 5' __lowerCamelCase : Union[str, Any] = {'x': 3} __lowerCamelCase : Tuple = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'y': 2}) __lowerCamelCase : Any = {'x': 8} __lowerCamelCase : Union[str, Any] = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 8, 'y': 5}) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : str = 'test_list = [x, add_two(x)]' __lowerCamelCase : List[Any] = {'x': 3} __lowerCamelCase : Union[str, Any] = evaluate(SCREAMING_SNAKE_CASE__ ,{'add_two': add_two} ,state=SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ ,[3, 5]) self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'test_list': [3, 5]}) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : List[Any] = 'y = x' __lowerCamelCase : Dict = {'x': 3} __lowerCamelCase : Any = evaluate(SCREAMING_SNAKE_CASE__ ,{} ,state=SCREAMING_SNAKE_CASE__) assert result == 3 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'y': 3}) def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Optional[int] = 'test_list = [x, add_two(x)]\ntest_list[1]' __lowerCamelCase : List[Any] = {'x': 3} __lowerCamelCase : Any = evaluate(SCREAMING_SNAKE_CASE__ ,{'add_two': add_two} ,state=SCREAMING_SNAKE_CASE__) assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'test_list': [3, 5]}) __lowerCamelCase : Optional[int] = 'test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']' __lowerCamelCase : Union[str, Any] = {'x': 3} __lowerCamelCase : Any = evaluate(SCREAMING_SNAKE_CASE__ ,{'add_two': add_two} ,state=SCREAMING_SNAKE_CASE__) assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 3, 'test_dict': {'x': 3, 'y': 5}}) def lowerCAmelCase ( self : Optional[int]): __lowerCamelCase : Optional[Any] = 'x = 0\nfor i in range(3):\n x = i' __lowerCamelCase : List[str] = {} __lowerCamelCase : List[Any] = evaluate(SCREAMING_SNAKE_CASE__ ,{'range': range} ,state=SCREAMING_SNAKE_CASE__) assert result == 2 self.assertDictEqual(SCREAMING_SNAKE_CASE__ ,{'x': 2, 'i': 2})
73
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): 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 ,SCREAMING_SNAKE_CASE__) * ((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(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[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 lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): 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 : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,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
73
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig a =logging.get_logger(__name__) # General docstring a ="""ResNetConfig""" # Base docstring a ="""microsoft/resnet-50""" a =[1, 2048, 7, 7] # Image classification docstring a ="""microsoft/resnet-50""" a ="""tiger cat""" a =[ """microsoft/resnet-50""", # See all resnet models at https://huggingface.co/models?filter=resnet ] class A_ ( nn.Module ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 3 ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : str = "relu"): super().__init__() __lowerCamelCase : str = nn.Convad( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,padding=kernel_size // 2 ,bias=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = nn.BatchNormad(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = ACTaFN[activation] if activation is not None else nn.Identity() def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tensor): __lowerCamelCase : Any = self.convolution(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.normalization(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( nn.Module ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : ResNetConfig): super().__init__() __lowerCamelCase : Optional[int] = ResNetConvLayer( config.num_channels ,config.embedding_size ,kernel_size=7 ,stride=2 ,activation=config.hidden_act) __lowerCamelCase : Dict = nn.MaxPoolad(kernel_size=3 ,stride=2 ,padding=1) __lowerCamelCase : List[Any] = config.num_channels def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tensor): __lowerCamelCase : int = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.') __lowerCamelCase : List[str] = self.embedder(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.pooler(SCREAMING_SNAKE_CASE__) return embedding class A_ ( nn.Module ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2): super().__init__() __lowerCamelCase : str = nn.Convad(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,stride=SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Any = nn.BatchNormad(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tensor): __lowerCamelCase : Dict = self.convolution(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.normalization(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( nn.Module ): def __init__( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : str = "relu"): super().__init__() __lowerCamelCase : List[str] = in_channels != out_channels or stride != 1 __lowerCamelCase : Union[str, Any] = ( ResNetShortCut(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__) if should_apply_shortcut else nn.Identity() ) __lowerCamelCase : int = nn.Sequential( ResNetConvLayer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__) ,ResNetConvLayer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,activation=SCREAMING_SNAKE_CASE__) ,) __lowerCamelCase : str = ACTaFN[activation] def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[Any] = hidden_state __lowerCamelCase : Dict = self.layer(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : List[str] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( nn.Module ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 4): super().__init__() __lowerCamelCase : List[str] = in_channels != out_channels or stride != 1 __lowerCamelCase : Dict = out_channels // reduction __lowerCamelCase : Any = ( ResNetShortCut(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__) if should_apply_shortcut else nn.Identity() ) __lowerCamelCase : Dict = nn.Sequential( ResNetConvLayer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,kernel_size=1) ,ResNetConvLayer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__) ,ResNetConvLayer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,activation=SCREAMING_SNAKE_CASE__) ,) __lowerCamelCase : str = ACTaFN[activation] def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : List[Any] = hidden_state __lowerCamelCase : List[Any] = self.layer(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.shortcut(SCREAMING_SNAKE_CASE__) hidden_state += residual __lowerCamelCase : List[Any] = self.activation(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( nn.Module ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : ResNetConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int = 2 ,SCREAMING_SNAKE_CASE__ : int = 2 ,): super().__init__() __lowerCamelCase : List[str] = ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer __lowerCamelCase : Optional[Any] = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act) ,*[layer(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,activation=config.hidden_act) for _ in range(depth - 1)] ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tensor): __lowerCamelCase : Optional[int] = input for layer in self.layers: __lowerCamelCase : Any = layer(SCREAMING_SNAKE_CASE__) return hidden_state class A_ ( nn.Module ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : ResNetConfig): super().__init__() __lowerCamelCase : Tuple = nn.ModuleList([]) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( SCREAMING_SNAKE_CASE__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,)) __lowerCamelCase : Union[str, Any] = zip(config.hidden_sizes ,config.hidden_sizes[1:]) for (in_channels, out_channels), depth in zip(SCREAMING_SNAKE_CASE__ ,config.depths[1:]): self.stages.append(ResNetStage(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,depth=SCREAMING_SNAKE_CASE__)) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Tensor ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True): __lowerCamelCase : str = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Dict = hidden_states + (hidden_state,) __lowerCamelCase : str = stage_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : List[str] = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__ ,) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : int = ResNetConfig _UpperCAmelCase : Union[str, Any] = '''resnet''' _UpperCAmelCase : List[str] = '''pixel_values''' _UpperCAmelCase : Optional[int] = True def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Union[str, Any]): if isinstance(SCREAMING_SNAKE_CASE__ ,nn.Convad): nn.init.kaiming_normal_(module.weight ,mode='fan_out' ,nonlinearity='relu') elif isinstance(SCREAMING_SNAKE_CASE__ ,(nn.BatchNormad, nn.GroupNorm)): nn.init.constant_(module.weight ,1) nn.init.constant_(module.bias ,0) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int=False): if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Tuple = value a =r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare ResNet model outputting raw features without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : int): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = config __lowerCamelCase : Tuple = ResNetEmbeddings(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = ResNetEncoder(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = nn.AdaptiveAvgPoolad((1, 1)) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None): __lowerCamelCase : List[str] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : List[Any] = self.embedder(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = self.encoder( SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = encoder_outputs[0] __lowerCamelCase : Dict = self.pooler(SCREAMING_SNAKE_CASE__) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=encoder_outputs.hidden_states ,) @add_start_docstrings( ''' ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = config.num_labels __lowerCamelCase : Optional[int] = ResNetModel(SCREAMING_SNAKE_CASE__) # classification head __lowerCamelCase : Optional[int] = nn.Sequential( nn.Flatten() ,nn.Linear(config.hidden_sizes[-1] ,config.num_labels) if config.num_labels > 0 else nn.Identity() ,) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[torch.FloatTensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.LongTensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : List[str] = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Any = self.resnet(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[Any] = self.classifier(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Optional[int] = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : Tuple = 'single_label_classification' else: __lowerCamelCase : Any = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : List[str] = MSELoss() if self.num_labels == 1: __lowerCamelCase : Tuple = loss_fct(logits.squeeze() ,labels.squeeze()) else: __lowerCamelCase : str = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : Tuple = CrossEntropyLoss() __lowerCamelCase : List[Any] = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : str = BCEWithLogitsLoss() __lowerCamelCase : Optional[Any] = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : Optional[Any] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states) @add_start_docstrings( ''' ResNet backbone, to be used with frameworks like DETR and MaskFormer. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Any): super().__init__(SCREAMING_SNAKE_CASE__) super()._init_backbone(SCREAMING_SNAKE_CASE__) __lowerCamelCase : int = [config.embedding_size] + config.hidden_sizes __lowerCamelCase : List[str] = ResNetEmbeddings(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = ResNetEncoder(SCREAMING_SNAKE_CASE__) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @replace_return_docstrings(output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Tensor ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None): __lowerCamelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : int = self.embedder(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.encoder(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = outputs.hidden_states __lowerCamelCase : Optional[int] = () for idx, stage in enumerate(self.stage_names): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: __lowerCamelCase : Tuple = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states if output_hidden_states else None ,attentions=SCREAMING_SNAKE_CASE__ ,)
73
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
1
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: __lowerCamelCase : Optional[int] = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: __lowerCamelCase : str = 0 while b > 0: if b & 1: __lowerCamelCase : Tuple = ((res % c) + (a % c)) % c a += a b >>= 1 return res
73
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
1
import argparse from collections import defaultdict def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : List[str] = F"{file}_{class_name}_{test_name}" done_test[_id] += 1 with open(lowerCamelCase__ , 'r' ) as f: __lowerCamelCase : Tuple = f.readlines() __lowerCamelCase : Optional[Any] = F"class {class_name}(" __lowerCamelCase : Tuple = F"{4 * ' '}def {test_name}(" __lowerCamelCase : List[str] = F"{8 * ' '}{correct_line.split()[0]}" __lowerCamelCase : Union[str, Any] = F"{1_6 * ' '}{correct_line.split()[0]}" __lowerCamelCase : List[str] = False __lowerCamelCase : List[str] = False __lowerCamelCase : List[str] = False __lowerCamelCase : Any = False __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Union[str, Any] = 0 __lowerCamelCase : Dict = [] for line in lines: if line.startswith(lowerCamelCase__ ): __lowerCamelCase : int = True elif in_class and line.startswith(lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = True elif in_class and in_func and (line.startswith(lowerCamelCase__ ) or line.startswith(lowerCamelCase__ )): __lowerCamelCase : Dict = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: __lowerCamelCase : int = True if in_class and in_func and in_line: if ")" not in line: continue else: __lowerCamelCase : int = True if in_class and in_func and in_line and insert_line: new_lines.append(F"{spaces * ' '}{correct_line}" ) __lowerCamelCase : int = False else: new_lines.append(lowerCamelCase__ ) with open(lowerCamelCase__ , 'w' ) as f: for line in new_lines: f.write(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__=None ) -> Union[str, Any]: if fail is not None: with open(lowerCamelCase__ , 'r' ) as f: __lowerCamelCase : str = {l.strip() for l in f.readlines()} else: __lowerCamelCase : List[Any] = None with open(lowerCamelCase__ , 'r' ) as f: __lowerCamelCase : Optional[Any] = f.readlines() __lowerCamelCase : Union[str, Any] = defaultdict(lowerCamelCase__ ) for line in correct_lines: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = line.split(';' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": a =argparse.ArgumentParser() parser.add_argument("""--correct_filename""", help="""filename of tests with expected result""") parser.add_argument("""--fail_filename""", help="""filename of test failures""", type=str, default=None) a =parser.parse_args() main(args.correct_filename, args.fail_filename)
73
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
1