code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): def __init__(self , *_lowercase , **_lowercase ): '''simple docstring''' warnings.warn( """The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DPTImageProcessor instead.""" , __a , ) super().__init__(*__a , **__a )
717
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowercase__ = logging.get_logger(__name__) lowercase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRContextEncoderTokenizer class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRQuestionEncoderTokenizer lowercase__ = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) lowercase__ = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) lowercase__ = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ : def __call__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , **_lowercase , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) elif titles is None or texts is None: __a : str = titles if texts is None else texts return super().__call__( _lowercase , _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) __a : str = titles if not isinstance(_lowercase , _lowercase ) else [titles] __a : Optional[Any] = texts if not isinstance(_lowercase , _lowercase ) else [texts] __a : Tuple = len(_lowercase ) __a : Dict = questions if not isinstance(_lowercase , _lowercase ) else [questions] * n_passages assert len(_lowercase ) == len( _lowercase ), F'''There should be as many titles than texts but got {len(_lowercase )} titles and {len(_lowercase )} texts.''' __a : Optional[Any] = super().__call__(_lowercase , _lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : str = super().__call__(_lowercase , add_special_tokens=_lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : Union[str, Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowercase , _lowercase ) ] } if return_attention_mask is not False: __a : Optional[int] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __a : str = attention_mask return self.pad(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 16 , _lowercase = 64 , _lowercase = 4 , ): '''simple docstring''' __a : Union[str, Any] = reader_input["""input_ids"""] __a , __a , __a : Optional[int] = reader_output[:3] __a : int = len(_lowercase ) __a : Any = sorted(range(_lowercase ) , reverse=_lowercase , key=relevance_logits.__getitem__ ) __a : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __a : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __a : Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __a : int = sequence_ids.index(self.pad_token_id ) else: __a : Optional[Any] = len(_lowercase ) __a : List[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowercase , top_spans=_lowercase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowercase , start_index=_lowercase , end_index=_lowercase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowercase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' __a : Tuple = [] for start_index, start_score in enumerate(_lowercase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __a : str = sorted(_lowercase , key=lambda _lowercase : x[1] , reverse=_lowercase ) __a : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' __a : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowercase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = ["input_ids", "attention_mask"] _lowerCAmelCase = DPRReaderTokenizer
63
0
"""simple docstring""" import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE__ ( nn.Module ): _lowerCAmelCase = 4_2 _lowerCAmelCase = jnp.floataa def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__(self , _lowercase ): '''simple docstring''' __a , __a , __a , __a : Union[str, Any] = hidden_states.shape __a : List[str] = jax.image.resize( __A , shape=(batch, height * 2, width * 2, channels) , method="""nearest""" , ) __a : Any = self.conv(__A ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): _lowerCAmelCase = 4_2 _lowerCAmelCase = jnp.floataa def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__(self , _lowercase ): '''simple docstring''' __a : List[Any] = self.conv(__A ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): _lowerCAmelCase = 4_2 _lowerCAmelCase = None _lowerCAmelCase = 0.0 _lowerCAmelCase = None _lowerCAmelCase = jnp.floataa def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = self.in_channels if self.out_channels is None else self.out_channels __a : Optional[int] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) __a : Tuple = nn.Conv( __A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __a : Dict = nn.Dense(__A , dtype=self.dtype ) __a : Union[str, Any] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) __a : Optional[Any] = nn.Dropout(self.dropout_prob ) __a : Dict = nn.Conv( __A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __a : Optional[Any] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut __a : List[str] = None if use_nin_shortcut: __a : List[str] = nn.Conv( __A , kernel_size=(1, 1) , strides=(1, 1) , padding="""VALID""" , dtype=self.dtype , ) def __call__(self , _lowercase , _lowercase , _lowercase=True ): '''simple docstring''' __a : Any = hidden_states __a : int = self.norma(__A ) __a : str = nn.swish(__A ) __a : Any = self.conva(__A ) __a : List[str] = self.time_emb_proj(nn.swish(__A ) ) __a : Dict = jnp.expand_dims(jnp.expand_dims(__A , 1 ) , 1 ) __a : int = hidden_states + temb __a : Union[str, Any] = self.norma(__A ) __a : Dict = nn.swish(__A ) __a : Union[str, Any] = self.dropout(__A , __A ) __a : Optional[int] = self.conva(__A ) if self.conv_shortcut is not None: __a : Dict = self.conv_shortcut(__A ) return hidden_states + residual
718
"""simple docstring""" import os def __magic_name__ ( _lowerCamelCase : Dict ): __a : List[str] = len(grid[0] ) __a : int = len(_lowerCamelCase ) __a : Tuple = 0 __a : List[Any] = 0 __a : List[str] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_lowerCamelCase ): for j in range(n_rows - 3 ): __a : List[Any] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] __a : Tuple = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: __a : List[Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: __a : List[Any] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) __a : str = max( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if max_product > largest: __a : Optional[Any] = max_product return largest def __magic_name__ ( ): __a : Tuple = [] with open(os.path.dirname(_lowerCamelCase ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) __a : Tuple = [[int(_lowerCamelCase ) for i in grid[j]] for j in range(len(_lowerCamelCase ) )] return largest_product(_lowerCamelCase ) if __name__ == "__main__": print(solution())
63
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowercase__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
719
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 42 _lowerCAmelCase = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
63
0
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class SCREAMING_SNAKE_CASE__ ( __SCREAMING_SNAKE_CASE ): _lowerCAmelCase = 42 _lowerCAmelCase = 42 class SCREAMING_SNAKE_CASE__ ( nn.Module ): _lowerCAmelCase = 42 _lowerCAmelCase = (1_6, 3_2, 9_6, 2_5_6) _lowerCAmelCase = jnp.floataa def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __a : int = [] for i in range(len(self.block_out_channels ) - 1 ): __a : Tuple = self.block_out_channels[i] __a : List[str] = self.block_out_channels[i + 1] __a : List[str] = nn.Conv( _a , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_a ) __a : List[str] = nn.Conv( _a , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_a ) __a : Dict = blocks __a : Optional[Any] = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self , _lowercase ): '''simple docstring''' __a : str = self.conv_in(_a ) __a : Optional[Any] = nn.silu(_a ) for block in self.blocks: __a : Optional[Any] = block(_a ) __a : str = nn.silu(_a ) __a : int = self.conv_out(_a ) return embedding @flax_register_to_config class SCREAMING_SNAKE_CASE__ ( nn.Module , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _lowerCAmelCase = 3_2 _lowerCAmelCase = 4 _lowerCAmelCase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _lowerCAmelCase = False _lowerCAmelCase = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) _lowerCAmelCase = 2 _lowerCAmelCase = 8 _lowerCAmelCase = None _lowerCAmelCase = 1_2_8_0 _lowerCAmelCase = 0.0 _lowerCAmelCase = False _lowerCAmelCase = jnp.floataa _lowerCAmelCase = True _lowerCAmelCase = 0 _lowerCAmelCase = "rgb" _lowerCAmelCase = (1_6, 3_2, 9_6, 2_5_6) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : str = (1, self.in_channels, self.sample_size, self.sample_size) __a : int = jnp.zeros(_a , dtype=jnp.floataa ) __a : Optional[Any] = jnp.ones((1,) , dtype=jnp.intaa ) __a : List[str] = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) __a : str = (1, 3, self.sample_size * 8, self.sample_size * 8) __a : str = jnp.zeros(_a , dtype=jnp.floataa ) __a , __a : Optional[int] = jax.random.split(_a ) __a : Dict = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_a , _a , _a , _a , _a )["params"] def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.block_out_channels __a : Union[str, Any] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __a : Union[str, Any] = self.num_attention_heads or self.attention_head_dim # input __a : Tuple = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __a : Optional[int] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) __a : Optional[int] = FlaxTimestepEmbedding(_a , dtype=self.dtype ) __a : Union[str, Any] = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) __a : Union[str, Any] = self.only_cross_attention if isinstance(_a , _a ): __a : List[Any] = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_a , _a ): __a : int = (num_attention_heads,) * len(self.down_block_types ) # down __a : str = [] __a : Union[str, Any] = [] __a : Optional[Any] = block_out_channels[0] __a : Union[str, Any] = nn.Conv( _a , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_a ) for i, down_block_type in enumerate(self.down_block_types ): __a : List[str] = output_channel __a : Dict = block_out_channels[i] __a : Optional[Any] = i == len(_a ) - 1 if down_block_type == "CrossAttnDownBlock2D": __a : Tuple = FlaxCrossAttnDownBlockaD( in_channels=_a , out_channels=_a , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: __a : Tuple = FlaxDownBlockaD( in_channels=_a , out_channels=_a , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_a ) for _ in range(self.layers_per_block ): __a : List[str] = nn.Conv( _a , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_a ) if not is_final_block: __a : Optional[Any] = nn.Conv( _a , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_a ) __a : Optional[int] = down_blocks __a : int = controlnet_down_blocks # mid __a : Optional[int] = block_out_channels[-1] __a : Union[str, Any] = FlaxUNetMidBlockaDCrossAttn( in_channels=_a , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) __a : Tuple = nn.Conv( _a , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase = 1.0 , _lowercase = True , _lowercase = False , ): '''simple docstring''' __a : Dict = self.controlnet_conditioning_channel_order if channel_order == "bgr": __a : int = jnp.flip(_a , axis=1 ) # 1. time if not isinstance(_a , jnp.ndarray ): __a : Dict = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_a , jnp.ndarray ) and len(timesteps.shape ) == 0: __a : Tuple = timesteps.astype(dtype=jnp.floataa ) __a : Union[str, Any] = jnp.expand_dims(_a , 0 ) __a : Optional[Any] = self.time_proj(_a ) __a : Dict = self.time_embedding(_a ) # 2. pre-process __a : Optional[int] = jnp.transpose(_a , (0, 2, 3, 1) ) __a : Union[str, Any] = self.conv_in(_a ) __a : Dict = jnp.transpose(_a , (0, 2, 3, 1) ) __a : str = self.controlnet_cond_embedding(_a ) sample += controlnet_cond # 3. down __a : Dict = (sample,) for down_block in self.down_blocks: if isinstance(_a , _a ): __a , __a : Dict = down_block(_a , _a , _a , deterministic=not train ) else: __a , __a : Optional[Any] = down_block(_a , _a , deterministic=not train ) down_block_res_samples += res_samples # 4. mid __a : Any = self.mid_block(_a , _a , _a , deterministic=not train ) # 5. contronet blocks __a : List[Any] = () for down_block_res_sample, controlnet_block in zip(_a , self.controlnet_down_blocks ): __a : Tuple = controlnet_block(_a ) controlnet_down_block_res_samples += (down_block_res_sample,) __a : str = controlnet_down_block_res_samples __a : Dict = self.controlnet_mid_block(_a ) # 6. scaling __a : Any = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=_a , mid_block_res_sample=_a )
720
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _lowerCAmelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCAmelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowerCAmelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowerCAmelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Optional[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __a : int = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : List[str] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __a : Optional[int] = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Tuple = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __a : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : Union[str, Any] = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __a : Optional[int] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __a : List[str] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = pipeline("""text-classification""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : Union[str, Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = pipeline("""text-classification""" , framework="""tf""" ) __a : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Tuple = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = TextClassificationPipeline(model=_lowercase , tokenizer=_lowercase ) return text_classifier, ["HuggingFace is in", "This is another test"] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __a : Union[str, Any] = """HuggingFace is in""" __a : List[str] = text_classifier(_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __a : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __a : Dict = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}, {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __a : Dict = text_classifier(_lowercase , top_k=_lowercase ) __a : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N, [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N] , ) __a : Dict = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __a : Any = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __a : Dict = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(_lowercase ): text_classifier(_lowercase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __a : Optional[int] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
63
0
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def __magic_name__ ( _lowerCamelCase : Optional[int] ): __a : Tuple = args.pruning_method __a : Optional[Any] = args.threshold __a : Tuple = args.model_name_or_path.rstrip("""/""" ) __a : List[Any] = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) __a : Union[str, Any] = torch.load(os.path.join(_lowerCamelCase , """pytorch_model.bin""" ) ) __a : List[Any] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __a : Tuple = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: __a : List[Any] = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: __a : Dict = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": __a : Dict = MagnitudeBinarizer.apply(inputs=_lowerCamelCase , threshold=_lowerCamelCase ) __a : Dict = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue __a : Union[str, Any] = name[:-6] __a : Union[str, Any] = model[F'''{prefix_}mask_scores'''] __a : Optional[Any] = TopKBinarizer.apply(_lowerCamelCase , _lowerCamelCase ) __a : int = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __a : List[str] = name[:-6] __a : Union[str, Any] = model[F'''{prefix_}mask_scores'''] __a : List[str] = ThresholdBinarizer.apply(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Optional[int] = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue __a : int = name[:-6] __a : str = model[F'''{prefix_}mask_scores'''] __a , __a : Optional[int] = -0.1, 1.1 __a : Dict = torch.sigmoid(_lowerCamelCase ) __a : Union[str, Any] = s * (r - l) + l __a : Optional[int] = s_bar.clamp(min=0.0 , max=1.0 ) __a : Tuple = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError("""Unknown pruning method""" ) if target_model_path is None: __a : Union[str, Any] = os.path.join( os.path.dirname(_lowerCamelCase ) , F'''bertarized_{os.path.basename(_lowerCamelCase )}''' ) if not os.path.isdir(_lowerCamelCase ): shutil.copytree(_lowerCamelCase , _lowerCamelCase ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(_lowerCamelCase , os.path.join(_lowerCamelCase , """pytorch_model.bin""" ) ) print("""\nPruned model saved! See you later!""" ) if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( "--pruning_method", choices=["l0", "magnitude", "topK", "sigmoied_threshold"], type=str, required=True, help=( "Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning," " sigmoied_threshold = Soft movement pruning)" ), ) parser.add_argument( "--threshold", type=float, required=False, help=( "For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model." "For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared." "Not needed for `l0`" ), ) parser.add_argument( "--model_name_or_path", type=str, required=True, help="Folder containing the model that was previously fine-pruned", ) parser.add_argument( "--target_model_path", default=None, type=str, required=False, help="Folder containing the model that was previously fine-pruned", ) lowercase__ = parser.parse_args() main(args)
721
"""simple docstring""" import unittest from knapsack import knapsack as k class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : str = 0 __a : Optional[Any] = [0] __a : int = [0] __a : str = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) __a : int = [60] __a : Union[str, Any] = [10] __a : Tuple = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = 3 __a : str = [1, 2, 3] __a : Optional[Any] = [3, 2, 1] __a : int = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 50 __a : Tuple = [60, 100, 120] __a : List[str] = [10, 20, 30] __a : Union[str, Any] = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 ) if __name__ == "__main__": unittest.main()
63
0
"""simple docstring""" import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def __magic_name__ ( _lowerCamelCase : Dict ): __a : Any = {} __a : Union[str, Any] = tokenizer(example["""content"""] , truncation=_lowerCamelCase )["""input_ids"""] __a : int = len(example["""content"""] ) / len(output["""input_ids"""] ) return output lowercase__ = HfArgumentParser(PretokenizationArguments) lowercase__ = parser.parse_args() if args.num_workers is None: lowercase__ = multiprocessing.cpu_count() lowercase__ = AutoTokenizer.from_pretrained(args.tokenizer_dir) lowercase__ = time.time() lowercase__ = load_dataset(args.dataset_name, split="train") print(f'Dataset loaded in {time.time()-t_start:.2f}s') lowercase__ = time.time() lowercase__ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ "repo_name", "path", "copies", "size", "content", "license", "hash", "line_mean", "line_max", "alpha_frac", "autogenerated", ], ) print(f'Dataset tokenized in {time.time()-t_start:.2f}s') lowercase__ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(f'Data pushed to the hub in {time.time()-t_start:.2f}s')
700
"""simple docstring""" from manim import * class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = Rectangle(height=0.5 , width=0.5 ) __a : Union[str, Any] = Rectangle(height=0.25 , width=0.25 ) __a : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a : Dict = [mem.copy() for i in range(6 )] __a : str = [mem.copy() for i in range(6 )] __a : Tuple = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Union[str, Any] = Text("""CPU""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(4 )] __a : Dict = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = Text("""GPU""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) gpu.move_to([-1, -1, 0] ) self.add(_lowercase ) __a : List[Any] = [mem.copy() for i in range(6 )] __a : Any = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Optional[Any] = Text("""Model""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) model.move_to([3, -1.0, 0] ) self.add(_lowercase ) __a : Tuple = [] __a : Tuple = [] __a : Optional[int] = [] for i, rect in enumerate(_lowercase ): rect.set_stroke(_lowercase ) __a : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_lowercase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowercase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_lowercase , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_lowercase , buff=0.0 ) self.add(_lowercase ) model_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase , *_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(6 )] __a : Union[str, Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Any = Text("""Loaded Checkpoint""" , font_size=24 ) __a : str = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) checkpoint.move_to([3, 0.5, 0] ) self.add(_lowercase ) __a : Dict = [] __a : int = [] for i, rect in enumerate(_lowercase ): __a : List[str] = fill.copy().set_fill(_lowercase , opacity=0.7 ) target.move_to(_lowercase ) ckpt_arr.append(_lowercase ) __a : Union[str, Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase ) __a : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a : List[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_lowercase , _lowercase ) __a : str = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_lowercase ) __a : Optional[int] = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) __a : List[Any] = [meta_mem.copy() for i in range(6 )] __a : Optional[int] = [meta_mem.copy() for i in range(6 )] __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Tuple = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Dict = Text("""Disk""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_lowercase , run_time=3 ) , Write(_lowercase , run_time=1 ) , Create(_lowercase , run_time=1 ) ) __a : Optional[Any] = [] for i, rect in enumerate(_lowercase ): __a : List[str] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_lowercase , run_time=1.5 ) ) self.play(*_lowercase ) self.play(FadeOut(_lowercase ) ) __a : List[str] = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_lowercase , run_time=3 ) ) self.play( FadeOut(_lowercase , _lowercase , *_lowercase , *_lowercase ) , ) self.wait()
63
0
"""simple docstring""" import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(">=", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType lowercase__ = get_logger(__name__) def __magic_name__ ( _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __a : Optional[Any] = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __a : List[Any] = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin''' __a : Tuple = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F'''Saving model to {output_model_file}''' ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __a : Union[str, Any] = ( F'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) __a : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Saving model to {output_model_file}''' ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __a : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , F'''{MODEL_NAME}_{model_index}''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F'''Saving model to {ckpt_dir}''' ) __a : Optional[int] = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F'''Model saved to {ckpt_dir}''' ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : List[Any] , _lowerCamelCase : Tuple=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( """Set the `sync_module_states` flag to `True` so that model states are synced across processes when """ """initializing FSDP object""" ) return __a : Optional[Any] = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin''' __a : int = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Loading model from {input_model_file}''' ) __a : int = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __a : List[Any] = ( F'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) __a : str = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Loading model from {input_model_file}''' ) __a : Optional[Any] = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __a : Dict = ( os.path.join(SCREAMING_SNAKE_CASE_ , F'''{MODEL_NAME}_{model_index}''' ) if F'''{MODEL_NAME}''' not in input_dir else input_dir ) logger.info(F'''Loading model from {ckpt_dir}''' ) __a : Union[str, Any] = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) __a : Dict = state_dict["model"] logger.info(F'''Model loaded from {ckpt_dir}''' ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : Optional[int] , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[int]=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __a : List[Any] = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __a : Union[str, Any] = ( F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) __a : Any = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Saving Optimizer state to {output_optimizer_file}''' ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Optimizer state saved in {output_optimizer_file}''' ) else: __a : Any = os.path.join(SCREAMING_SNAKE_CASE_ , F'''{OPTIMIZER_NAME}_{optimizer_index}''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F'''Saving Optimizer state to {ckpt_dir}''' ) dist_cp.save_state_dict( state_dict={"""optimizer""": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F'''Optimizer state saved in {ckpt_dir}''' ) def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[Any]=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __a : int = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __a : Tuple = ( F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) __a : Dict = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F'''Loading Optimizer state from {input_optimizer_file}''' ) __a : Optional[Any] = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F'''Optimizer state loaded from {input_optimizer_file}''' ) else: __a : Tuple = ( os.path.join(SCREAMING_SNAKE_CASE_ , F'''{OPTIMIZER_NAME}_{optimizer_index}''' ) if F'''{OPTIMIZER_NAME}''' not in input_dir else input_dir ) logger.info(F'''Loading Optimizer from {ckpt_dir}''' ) __a : Dict = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="""optimizer""" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) __a : Union[str, Any] = optim_state["optimizer"] logger.info(F'''Optimizer loaded from {ckpt_dir}''' ) __a : int = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
701
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float(moles / volume ) * nfactor ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (volume) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (pressure) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((pressure * volume) / (0.08_21 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
from __future__ import annotations from random import random from typing import Generic, TypeVar lowercase__ = TypeVar("KT") lowercase__ = TypeVar("VT") class SCREAMING_SNAKE_CASE__ ( Generic[KT, VT] ): def __init__(self , _lowercase = "root" , _lowercase = None ): '''simple docstring''' __a : List[str] = key __a : Tuple = value __a : list[Node[KT, VT]] = [] def __repr__(self ): '''simple docstring''' return F'''Node({self.key}: {self.value})''' @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.forward ) class SCREAMING_SNAKE_CASE__ ( Generic[KT, VT] ): def __init__(self , _lowercase = 0.5 , _lowercase = 16 ): '''simple docstring''' __a : Node[KT, VT] = Node[KT, VT]() __a : Tuple = 0 __a : Tuple = p __a : List[Any] = max_level def __str__(self ): '''simple docstring''' __a : Optional[Any] = list(self ) if len(_lowercase ) == 0: return F'''SkipList(level={self.level})''' __a : List[str] = max((len(str(_lowercase ) ) for item in items) , default=4 ) __a : List[Any] = max(_lowercase , 4 ) + 4 __a : List[str] = self.head __a : List[str] = [] __a : Optional[Any] = node.forward.copy() lines.append(F'''[{node.key}]'''.ljust(_lowercase , """-""" ) + """* """ * len(_lowercase ) ) lines.append(""" """ * label_size + """| """ * len(_lowercase ) ) while len(node.forward ) != 0: __a : Tuple = node.forward[0] lines.append( F'''[{node.key}]'''.ljust(_lowercase , """-""" ) + """ """.join(str(n.key ) if n.key == node.key else """|""" for n in forwards ) ) lines.append(""" """ * label_size + """| """ * len(_lowercase ) ) __a : Tuple = node.forward lines.append("""None""".ljust(_lowercase ) + """* """ * len(_lowercase ) ) return F'''SkipList(level={self.level})\n''' + "\n".join(_lowercase ) def __iter__(self ): '''simple docstring''' __a : int = self.head while len(node.forward ) != 0: yield node.forward[0].key __a : List[Any] = node.forward[0] def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = 1 while random() < self.p and level < self.max_level: level += 1 return level def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[str] = [] __a : int = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: __a : List[str] = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(_lowercase ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : Dict = self._locate_node(_lowercase ) if node is not None: for i, update_node in enumerate(_lowercase ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: __a : str = node.forward[i] else: __a : List[str] = update_node.forward[:i] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = self._locate_node(_lowercase ) if node is not None: __a : Union[str, Any] = value else: __a : int = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , _lowercase ): update_vector.append(self.head ) __a : List[Any] = level __a : List[Any] = Node(_lowercase , _lowercase ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(_lowercase ) else: __a : Any = new_node def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[str] = self._locate_node(_lowercase ) if node is not None: return node.value return None def __magic_name__ ( ): __a : Tuple = SkipList() skip_list.insert("""Key1""" , 3 ) skip_list.insert("""Key2""" , 1_2 ) skip_list.insert("""Key3""" , 4_1 ) skip_list.insert("""Key4""" , -1_9 ) __a : Optional[int] = skip_list.head __a : Optional[Any] = {} while node.level != 0: __a : int = node.forward[0] __a : Any = node.value assert len(SCREAMING_SNAKE_CASE_ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 1_2 assert all_values["Key3"] == 4_1 assert all_values["Key4"] == -1_9 def __magic_name__ ( ): __a : int = SkipList() skip_list.insert("""Key1""" , 1_0 ) skip_list.insert("""Key1""" , 1_2 ) skip_list.insert("""Key5""" , 7 ) skip_list.insert("""Key7""" , 1_0 ) skip_list.insert("""Key10""" , 5 ) skip_list.insert("""Key7""" , 7 ) skip_list.insert("""Key5""" , 5 ) skip_list.insert("""Key10""" , 1_0 ) __a : Union[str, Any] = skip_list.head __a : Tuple = {} while node.level != 0: __a : List[Any] = node.forward[0] __a : int = node.value if len(SCREAMING_SNAKE_CASE_ ) != 4: print() assert len(SCREAMING_SNAKE_CASE_ ) == 4 assert all_values["Key1"] == 1_2 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 1_0 def __magic_name__ ( ): __a : int = SkipList() assert skip_list.find("""Some key""" ) is None def __magic_name__ ( ): __a : Optional[int] = SkipList() skip_list.insert("""Key2""" , 2_0 ) assert skip_list.find("""Key2""" ) == 2_0 skip_list.insert("""Some Key""" , 1_0 ) skip_list.insert("""Key2""" , 8 ) skip_list.insert("""V""" , 1_3 ) assert skip_list.find("""Y""" ) is None assert skip_list.find("""Key2""" ) == 8 assert skip_list.find("""Some Key""" ) == 1_0 assert skip_list.find("""V""" ) == 1_3 def __magic_name__ ( ): __a : Any = SkipList() skip_list.delete("""Some key""" ) assert len(skip_list.head.forward ) == 0 def __magic_name__ ( ): __a : Optional[Any] = SkipList() skip_list.insert("""Key1""" , 1_2 ) skip_list.insert("""V""" , 1_3 ) skip_list.insert("""X""" , 1_4 ) skip_list.insert("""Key2""" , 1_5 ) skip_list.delete("""V""" ) skip_list.delete("""Key2""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""Key2""" ) is None def __magic_name__ ( ): __a : Union[str, Any] = SkipList() skip_list.insert("""Key1""" , 1_2 ) skip_list.insert("""V""" , 1_3 ) skip_list.insert("""X""" , 1_4 ) skip_list.insert("""Key2""" , 1_5 ) skip_list.delete("""V""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) == 1_4 assert skip_list.find("""Key1""" ) == 1_2 assert skip_list.find("""Key2""" ) == 1_5 skip_list.delete("""X""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) == 1_2 assert skip_list.find("""Key2""" ) == 1_5 skip_list.delete("""Key1""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) is None assert skip_list.find("""Key2""" ) == 1_5 skip_list.delete("""Key2""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) is None assert skip_list.find("""Key2""" ) is None def __magic_name__ ( ): __a : List[Any] = SkipList() skip_list.insert("""Key1""" , 1_2 ) skip_list.insert("""V""" , 1_3 ) skip_list.insert("""X""" , 1_4_2 ) skip_list.insert("""Key2""" , 1_5 ) skip_list.delete("""X""" ) def traverse_keys(_lowerCamelCase : List[str] ): yield node.key for forward_node in node.forward: yield from traverse_keys(SCREAMING_SNAKE_CASE_ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def __magic_name__ ( ): def is_sorted(_lowerCamelCase : int ): return all(next_item >= item for item, next_item in zip(SCREAMING_SNAKE_CASE_ , lst[1:] ) ) __a : int = SkipList() for i in range(1_0 ): skip_list.insert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert is_sorted(list(SCREAMING_SNAKE_CASE_ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(SCREAMING_SNAKE_CASE_ ) ) skip_list.insert(-1_2 , -1_2 ) skip_list.insert(7_7 , 7_7 ) assert is_sorted(list(SCREAMING_SNAKE_CASE_ ) ) def __magic_name__ ( ): for _ in range(1_0_0 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def __magic_name__ ( ): __a : int = SkipList() skip_list.insert(2 , """2""" ) skip_list.insert(4 , """4""" ) skip_list.insert(6 , """4""" ) skip_list.insert(4 , """5""" ) skip_list.insert(8 , """4""" ) skip_list.insert(9 , """4""" ) skip_list.delete(4 ) print(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
702
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : list[int] ): if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) __a : Any = sum(_lowerCamelCase ) / len(_lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowercase__ = logging.get_logger(__name__) lowercase__ = { "microsoft/conditional-detr-resnet-50": ( "https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE__ ( __A ): _lowerCAmelCase = "conditional_detr" _lowerCAmelCase = ["past_key_values"] _lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__(self , _lowercase=True , _lowercase=None , _lowercase=3 , _lowercase=300 , _lowercase=6 , _lowercase=2048 , _lowercase=8 , _lowercase=6 , _lowercase=2048 , _lowercase=8 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=True , _lowercase="relu" , _lowercase=256 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1.0 , _lowercase=False , _lowercase="sine" , _lowercase="resnet50" , _lowercase=True , _lowercase=False , _lowercase=2 , _lowercase=5 , _lowercase=2 , _lowercase=1 , _lowercase=1 , _lowercase=2 , _lowercase=5 , _lowercase=2 , _lowercase=0.25 , **_lowercase , ): '''simple docstring''' if backbone_config is not None and use_timm_backbone: raise ValueError("""You can\'t specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) __a : Union[str, Any] = CONFIG_MAPPING['resnet'](out_features=["""stage4"""] ) elif isinstance(_lowercase , _lowercase ): __a : int = backbone_config.get("""model_type""" ) __a : Any = CONFIG_MAPPING[backbone_model_type] __a : Tuple = config_class.from_dict(_lowercase ) __a : Optional[int] = use_timm_backbone __a : Dict = backbone_config __a : List[str] = num_channels __a : Dict = num_queries __a : Dict = d_model __a : str = encoder_ffn_dim __a : Optional[Any] = encoder_layers __a : str = encoder_attention_heads __a : Optional[int] = decoder_ffn_dim __a : Optional[int] = decoder_layers __a : List[Any] = decoder_attention_heads __a : Dict = dropout __a : Any = attention_dropout __a : Optional[int] = activation_dropout __a : Dict = activation_function __a : Optional[int] = init_std __a : Dict = init_xavier_std __a : Any = encoder_layerdrop __a : str = decoder_layerdrop __a : int = encoder_layers __a : str = auxiliary_loss __a : Optional[int] = position_embedding_type __a : List[str] = backbone __a : int = use_pretrained_backbone __a : Dict = dilation # Hungarian matcher __a : List[str] = class_cost __a : str = bbox_cost __a : Optional[Any] = giou_cost # Loss coefficients __a : Tuple = mask_loss_coefficient __a : Optional[int] = dice_loss_coefficient __a : List[str] = cls_loss_coefficient __a : Union[str, Any] = bbox_loss_coefficient __a : Union[str, Any] = giou_loss_coefficient __a : Optional[Any] = focal_alpha super().__init__(is_encoder_decoder=_lowercase , **_lowercase ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.encoder_attention_heads @property def lowerCAmelCase__(self ): '''simple docstring''' return self.d_model def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __a : List[Any] = self.backbone_config.to_dict() __a : Union[str, Any] = self.__class__.model_type return output class SCREAMING_SNAKE_CASE__ ( __A ): _lowerCAmelCase = version.parse("1.11" ) @property def lowerCAmelCase__(self ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 1e-5 @property def lowerCAmelCase__(self ): '''simple docstring''' return 12
703
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math.sqrt(_lowerCamelCase ) __a : Any = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): __a : Any = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float ): # Creates a gaussian kernel of given dimension. __a : int = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowerCamelCase ): for j in range(0 , _lowerCamelCase ): __a : Any = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int , ): __a : Tuple = np.zeros(img.shape ) __a : Optional[int] = get_gauss_kernel(_lowerCamelCase , _lowerCamelCase ) __a , __a : int = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): __a : List[str] = get_slice(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Any = img_s - img_s[kernel_size // 2, kernel_size // 2] __a : Optional[Any] = vec_gaussian(_lowerCamelCase , _lowerCamelCase ) __a : Optional[Any] = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Any = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Tuple = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) __a : Optional[Any] = val return imga def __magic_name__ ( _lowerCamelCase : list ): __a : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" __a : Union[str, Any] = float(args[2] ) if args[2:] else 1.0 __a : Optional[int] = float(args[3] ) if args[3:] else 1.0 if args[4:]: __a : Any = int(args[4] ) __a : Any = kernel_size + abs(kernel_size % 2 - 1 ) else: __a : Optional[int] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": lowercase__ , lowercase__ , lowercase__ , lowercase__ = parse_args(sys.argv) lowercase__ = cva.imread(filename, 0) cva.imshow("input image", img) lowercase__ = img / 255 lowercase__ = out.astype("float32") lowercase__ = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) lowercase__ = out * 255 lowercase__ = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
63
0
"""simple docstring""" 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 SCREAMING_SNAKE_CASE__ ( __lowercase ): _lowerCAmelCase = 4_2 _lowerCAmelCase = None def __magic_name__ ( _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=0.9_99 , _lowerCamelCase : Optional[int]="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(_lowerCamelCase : Dict ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_lowerCamelCase : str ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a : Dict = [] for i in range(__snake_case ): __a : int = i / num_diffusion_timesteps __a : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__snake_case ) / alpha_bar_fn(__snake_case ) , __snake_case ) ) return torch.tensor(__snake_case , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE__ ( __lowercase , __lowercase ): @register_to_config def __init__(self , _lowercase = 1000 , _lowercase = "fixed_small_log" , _lowercase = True , _lowercase = 1.0 , _lowercase = "epsilon" , _lowercase = "squaredcos_cap_v2" , ): '''simple docstring''' if beta_schedule != "squaredcos_cap_v2": raise ValueError("""UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'""" ) __a : List[Any] = betas_for_alpha_bar(_A ) __a : List[str] = 1.0 - self.betas __a : Optional[int] = torch.cumprod(self.alphas , dim=0 ) __a : Optional[Any] = torch.tensor(1.0 ) # standard deviation of the initial noise distribution __a : List[Any] = 1.0 # setable values __a : int = None __a : str = torch.from_numpy(np.arange(0 , _A )[::-1].copy() ) __a : str = variance_type def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' return sample def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' __a : Union[str, Any] = num_inference_steps __a : Optional[Any] = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) __a : Any = (np.arange(0 , _A ) * step_ratio).round()[::-1].copy().astype(np.intaa ) __a : Optional[Any] = torch.from_numpy(_A ).to(_A ) def lowerCAmelCase__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ): '''simple docstring''' if prev_timestep is None: __a : Any = t - 1 __a : Dict = self.alphas_cumprod[t] __a : Tuple = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __a : List[Any] = 1 - alpha_prod_t __a : Dict = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __a : int = self.betas[t] else: __a : List[Any] = 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 __a : Tuple = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: __a : int = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": __a : List[Any] = torch.log(torch.clamp(_A , min=1e-20 ) ) __a : List[Any] = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler __a : List[str] = variance.log() __a : List[Any] = beta.log() __a : Union[str, Any] = (predicted_variance + 1) / 2 __a : Optional[Any] = frac * max_log + (1 - frac) * min_log return variance def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase = None , _lowercase=None , _lowercase = True , ): '''simple docstring''' __a : Tuple = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": __a , __a : Union[str, Any] = torch.split(_A , sample.shape[1] , dim=1 ) else: __a : str = None # 1. compute alphas, betas if prev_timestep is None: __a : Dict = t - 1 __a : Dict = self.alphas_cumprod[t] __a : Any = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one __a : Optional[int] = 1 - alpha_prod_t __a : Optional[Any] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: __a : Any = self.betas[t] __a : List[Any] = self.alphas[t] else: __a : Optional[Any] = 1 - alpha_prod_t / alpha_prod_t_prev __a : int = 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": __a : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": __a : str = 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: __a : Dict = torch.clamp( _A , -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 __a : int = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t __a : 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 __a : Optional[int] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise __a : Optional[Any] = 0 if t > 0: __a : str = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=_A , device=model_output.device ) __a : List[str] = self._get_variance( _A , predicted_variance=_A , prev_timestep=_A , ) if self.variance_type == "fixed_small_log": __a : List[str] = variance elif self.variance_type == "learned_range": __a : 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.""" ) __a : List[str] = variance * variance_noise __a : int = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=_A , pred_original_sample=_A ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' __a : Tuple = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) __a : Any = timesteps.to(original_samples.device ) __a : List[Any] = alphas_cumprod[timesteps] ** 0.5 __a : Optional[int] = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): __a : List[str] = sqrt_alpha_prod.unsqueeze(-1 ) __a : int = (1 - alphas_cumprod[timesteps]) ** 0.5 __a : List[Any] = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): __a : int = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) __a : Union[str, Any] = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
704
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __magic_name__ ( ): __a : Dict = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 2_0, """a """ * 3_0, """b """ * 7], } __a : Optional[Any] = Dataset.from_dict(_lowerCamelCase ) return dataset class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = get_dataset() __a : List[Any] = make_duplicate_clusters(_lowercase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = get_dataset() __a , __a : Optional[Any] = deduplicate_dataset(_lowercase ) self.assertEqual(len(_lowercase ) , 2 ) print(_lowercase ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , _lowercase )
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : Tuple = 1_0_0 ): __a : Optional[Any] = 0 __a : int = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f'{solution() = }')
705
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available lowercase__ = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" from __future__ import annotations def __magic_name__ ( _lowerCamelCase : Dict , _lowerCamelCase : int , _lowerCamelCase : str , _lowerCamelCase : str ): if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): __a : int = array[indexa], array[indexa] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : List[str] ): if length > 1: __a : Optional[Any] = int(length / 2 ) for i in range(lowerCAmelCase_ , low + middle ): comp_and_swap(lowerCAmelCase_ , lowerCAmelCase_ , i + middle , lowerCAmelCase_ ) bitonic_merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) bitonic_merge(lowerCAmelCase_ , low + middle , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( _lowerCamelCase : List[str] , _lowerCamelCase : Tuple , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict ): if length > 1: __a : List[Any] = int(length / 2 ) bitonic_sort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , 1 ) bitonic_sort(lowerCAmelCase_ , low + middle , lowerCAmelCase_ , 0 ) bitonic_merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": lowercase__ = input("Enter numbers separated by a comma:\n").strip() lowercase__ = [int(item.strip()) for item in user_input.split(",")] bitonic_sort(unsorted, 0, len(unsorted), 1) print("\nSorted array in ascending order is: ", end="") print(*unsorted, sep=", ") bitonic_merge(unsorted, 0, len(unsorted), 0) print("Sorted array in descending order is: ", end="") print(*unsorted, sep=", ")
706
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "linear" _lowerCAmelCase = "cosine" _lowerCAmelCase = "cosine_with_restarts" _lowerCAmelCase = "polynomial" _lowerCAmelCase = "constant" _lowerCAmelCase = "constant_with_warmup" _lowerCAmelCase = "piecewise_constant" def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int = -1 ): return LambdaLR(_lowerCamelCase , lambda _lowerCamelCase : 1 , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1.0 , _lowerCamelCase ) ) return 1.0 return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : str , _lowerCamelCase : int = -1 ): __a : Optional[int] = {} __a : Any = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __a , __a : int = rule_str.split(""":""" ) __a : Optional[int] = int(_lowerCamelCase ) __a : str = float(_lowerCamelCase ) __a : int = value __a : Dict = float(rule_list[-1] ) def create_rules_function(_lowerCamelCase : str , _lowerCamelCase : Tuple ): def rule_func(_lowerCamelCase : int ) -> float: __a : Optional[Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(_lowerCamelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __a : Optional[int] = create_rules_function(_lowerCamelCase , _lowerCamelCase ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : str=-1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0.5 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Any ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(_lowerCamelCase ) * 2.0 * progress )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int = 1 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Optional[int] ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(_lowerCamelCase ) * progress) % 1.0) )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]=1E-7 , _lowerCamelCase : Optional[int]=1.0 , _lowerCamelCase : Optional[int]=-1 ): __a : Union[str, Any] = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __a : Tuple = lr_init - lr_end __a : int = num_training_steps - num_warmup_steps __a : Optional[int] = 1 - (current_step - num_warmup_steps) / decay_steps __a : List[str] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __magic_name__ ( _lowerCamelCase : Union[str, SchedulerType] , _lowerCamelCase : Optimizer , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 1 , _lowerCamelCase : float = 1.0 , _lowerCamelCase : int = -1 , ): __a : int = SchedulerType(_lowerCamelCase ) __a : Optional[int] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(_lowerCamelCase , last_epoch=_lowerCamelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(_lowerCamelCase , step_rules=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(_lowerCamelCase , num_warmup_steps=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , num_cycles=_lowerCamelCase , last_epoch=_lowerCamelCase , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , power=_lowerCamelCase , last_epoch=_lowerCamelCase , ) return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , last_epoch=_lowerCamelCase )
63
0
"""simple docstring""" import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase=13 , _lowercase=7 , _lowercase=True , _lowercase=True , _lowercase=False , _lowercase=True , _lowercase=99 , _lowercase=32 , _lowercase=5 , _lowercase=4 , _lowercase=37 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=512 , _lowercase=16 , _lowercase=2 , _lowercase=0.02 , _lowercase=3 , _lowercase=4 , _lowercase=None , ): '''simple docstring''' __a : Optional[int] = parent __a : List[Any] = batch_size __a : Any = seq_length __a : Optional[Any] = is_training __a : Dict = use_input_mask __a : Dict = use_token_type_ids __a : Optional[int] = use_labels __a : Dict = vocab_size __a : Tuple = hidden_size __a : Optional[Any] = num_hidden_layers __a : str = num_attention_heads __a : List[Any] = intermediate_size __a : List[str] = hidden_act __a : Any = hidden_dropout_prob __a : Dict = attention_probs_dropout_prob __a : Union[str, Any] = max_position_embeddings __a : str = type_vocab_size __a : List[str] = type_sequence_label_size __a : Dict = initializer_range __a : Union[str, Any] = num_labels __a : Tuple = num_choices __a : List[str] = scope def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : Optional[Any] = None if self.use_input_mask: __a : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __a : Optional[int] = None __a : Dict = None __a : List[str] = None if self.use_labels: __a : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : Any = ids_tensor([self.batch_size] , self.num_choices ) __a : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase__(self ): '''simple docstring''' return 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 , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = DistilBertModel(config=_lowercase ) model.to(_lowercase ) model.eval() __a : Union[str, Any] = model(_lowercase , _lowercase ) __a : int = model(_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = DistilBertForMaskedLM(config=_lowercase ) model.to(_lowercase ) model.eval() __a : List[Any] = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Any = DistilBertForQuestionAnswering(config=_lowercase ) model.to(_lowercase ) model.eval() __a : Optional[Any] = model( _lowercase , attention_mask=_lowercase , start_positions=_lowercase , end_positions=_lowercase ) 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 , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = self.num_labels __a : str = DistilBertForSequenceClassification(_lowercase ) model.to(_lowercase ) model.eval() __a : str = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Any = self.num_labels __a : Dict = DistilBertForTokenClassification(config=_lowercase ) model.to(_lowercase ) model.eval() __a : List[str] = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : List[Any] = self.num_choices __a : Tuple = DistilBertForMultipleChoice(config=_lowercase ) model.to(_lowercase ) model.eval() __a : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : List[Any] = model( _lowercase , attention_mask=_lowercase , labels=_lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ((__a) , (__a) , (__a) , (__a) , (__a) , (__a)) : Union[str, Any] = config_and_inputs __a : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) _lowerCAmelCase = ( { "feature-extraction": DistilBertModel, "fill-mask": DistilBertForMaskedLM, "question-answering": DistilBertForQuestionAnswering, "text-classification": DistilBertForSequenceClassification, "token-classification": DistilBertForTokenClassification, "zero-shot": DistilBertForSequenceClassification, } if is_torch_available() else {} ) _lowerCAmelCase = True _lowerCAmelCase = True _lowerCAmelCase = True _lowerCAmelCase = True def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = DistilBertModelTester(self ) __a : Optional[Any] = ConfigTester(self , config_class=_lowercase , dim=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[int] = DistilBertModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) @slow @require_torch_gpu def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return __a : List[Any] = True __a : Optional[int] = model_class(config=_lowercase ) __a : Union[str, Any] = self._prepare_for_class(_lowercase , _lowercase ) __a : List[Any] = torch.jit.trace( _lowercase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_lowercase , os.path.join(_lowercase , """traced_model.pt""" ) ) __a : Any = torch.jit.load(os.path.join(_lowercase , """traced_model.pt""" ) , map_location=_lowercase ) loaded(inputs_dict["""input_ids"""].to(_lowercase ) , inputs_dict["""attention_mask"""].to(_lowercase ) ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : int = DistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __a : List[str] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __a : Any = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : Optional[Any] = model(_lowercase , attention_mask=_lowercase )[0] __a : Dict = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _lowercase ) __a : Optional[int] = torch.tensor( [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowercase , atol=1e-4 ) )
707
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=False ): __a : Dict = OmegaConf.load(_lowerCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_lowerCamelCase ) ) ) return config def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : int=None ): if conf_path is None: __a : str = """./model_checkpoints/vqgan_only.yaml""" __a : List[Any] = load_config(_lowerCamelCase , display=_lowerCamelCase ) __a : Dict = VQModel(**config.model.params ) if ckpt_path is None: __a : List[Any] = """./model_checkpoints/vqgan_only.pt""" __a : Tuple = torch.load(_lowerCamelCase , map_location=_lowerCamelCase ) if ".ckpt" in ckpt_path: __a : List[str] = sd["""state_dict"""] model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase ) model.to(_lowerCamelCase ) del sd return model def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : List[str] ): __a , __a , __a : Tuple = model.encode(_lowerCamelCase ) print(F'''VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}''' ) __a : Union[str, Any] = model.decode(_lowerCamelCase ) return xrec def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any]=False ): __a , __a : Optional[Any] = string.rsplit(""".""" , 1 ) if reload: __a : Optional[Any] = importlib.import_module(_lowerCamelCase ) importlib.reload(_lowerCamelCase ) return getattr(importlib.import_module(_lowerCamelCase , package=_lowerCamelCase ) , cls ) def __magic_name__ ( _lowerCamelCase : Any ): if "target" not in config: raise KeyError("""Expected key `target` to instantiate.""" ) return get_obj_from_str(config["""target"""] )(**config.get("""params""" , {} ) ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Dict , _lowerCamelCase : int=True , _lowerCamelCase : int=True ): __a : Union[str, Any] = instantiate_from_config(_lowerCamelCase ) if sd is not None: model.load_state_dict(_lowerCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : int ): # load the specified checkpoint if ckpt: __a : List[str] = torch.load(_lowerCamelCase , map_location="""cpu""" ) __a : Any = pl_sd["""global_step"""] print(F'''loaded model from global step {global_step}.''' ) else: __a : List[Any] = {"""state_dict""": None} __a : Any = None __a : Union[str, Any] = load_model_from_config(config.model , pl_sd["""state_dict"""] , gpu=_lowerCamelCase , eval_mode=_lowerCamelCase )["""model"""] return model, global_step
63
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class SCREAMING_SNAKE_CASE__ ( lowerCAmelCase__ ): _lowerCAmelCase = "ctrl" _lowerCAmelCase = ["past_key_values"] _lowerCAmelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__(self , _lowercase=246534 , _lowercase=256 , _lowercase=1280 , _lowercase=8192 , _lowercase=48 , _lowercase=16 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=1e-6 , _lowercase=0.02 , _lowercase=True , **_lowercase , ): '''simple docstring''' __a : int = vocab_size __a : Union[str, Any] = n_positions __a : Optional[int] = n_embd __a : List[str] = n_layer __a : List[Any] = n_head __a : Dict = dff __a : Any = resid_pdrop __a : Union[str, Any] = embd_pdrop __a : int = layer_norm_epsilon __a : List[Any] = initializer_range __a : Any = use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
708
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase__ = { "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "LlamaForCausalLM", "LlamaModel", "LlamaPreTrainedModel", "LlamaForSequenceClassification", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase__ = abspath(join(dirname(dirname(__file__)), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def __magic_name__ ( _lowerCamelCase : Any ): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(A_ ) def __magic_name__ ( _lowerCamelCase : Dict ): from diffusers.utils.testing_utils import pytest_terminal_summary_main __a : str = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(A_ , id=A_ )
709
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "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 SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "unispeech" def __init__(self , _lowercase=32 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=1e-5 , _lowercase="group" , _lowercase="gelu" , _lowercase=(512, 512, 512, 512, 512, 512, 512) , _lowercase=(5, 2, 2, 2, 2, 2, 2) , _lowercase=(10, 3, 3, 3, 3, 2, 2) , _lowercase=False , _lowercase=128 , _lowercase=16 , _lowercase=False , _lowercase=True , _lowercase=0.05 , _lowercase=10 , _lowercase=2 , _lowercase=0.0 , _lowercase=10 , _lowercase=0 , _lowercase=320 , _lowercase=2 , _lowercase=0.1 , _lowercase=100 , _lowercase=256 , _lowercase=256 , _lowercase=0.1 , _lowercase="mean" , _lowercase=False , _lowercase=False , _lowercase=256 , _lowercase=80 , _lowercase=0 , _lowercase=1 , _lowercase=2 , _lowercase=0.5 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase ) __a : Union[str, Any] = hidden_size __a : Any = feat_extract_norm __a : Union[str, Any] = feat_extract_activation __a : Tuple = list(_lowercase ) __a : Dict = list(_lowercase ) __a : List[Any] = list(_lowercase ) __a : List[Any] = conv_bias __a : Optional[Any] = num_conv_pos_embeddings __a : Union[str, Any] = num_conv_pos_embedding_groups __a : Dict = len(self.conv_dim ) __a : Dict = num_hidden_layers __a : Union[str, Any] = intermediate_size __a : List[str] = hidden_act __a : int = num_attention_heads __a : int = hidden_dropout __a : Any = attention_dropout __a : List[Any] = activation_dropout __a : List[Any] = feat_proj_dropout __a : Union[str, Any] = final_dropout __a : str = layerdrop __a : Dict = layer_norm_eps __a : Dict = initializer_range __a : Union[str, Any] = num_ctc_classes __a : List[Any] = vocab_size __a : Any = do_stable_layer_norm __a : List[str] = use_weighted_layer_sum __a : List[str] = 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 __a : Dict = apply_spec_augment __a : Union[str, Any] = mask_time_prob __a : List[str] = mask_time_length __a : Dict = mask_time_min_masks __a : List[Any] = mask_feature_prob __a : Tuple = mask_feature_length __a : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __a : List[Any] = num_codevectors_per_group __a : Union[str, Any] = num_codevector_groups __a : List[Any] = contrastive_logits_temperature __a : Any = feat_quantizer_dropout __a : Optional[int] = num_negatives __a : List[str] = codevector_dim __a : List[Any] = proj_codevector_dim __a : Tuple = diversity_loss_weight # ctc loss __a : Any = ctc_loss_reduction __a : List[str] = ctc_zero_infinity # pretraining loss __a : Tuple = replace_prob @property def lowerCAmelCase__(self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
63
0
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 10 def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = [1, 2, 3, 4] __a : List[str] = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(_A , self.block_size , 0 ) , _A ) def lowerCAmelCase__(self ): '''simple docstring''' __a : str = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] __a : Tuple = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_A , self.block_size , 0 ) , _A ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] __a : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(_A , self.block_size , 0 ) , _A ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' __a : Optional[Any] = process_story(_A ) self.assertEqual(_A , [] ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = '' __a : List[Any] = process_story(_A ) self.assertEqual(_A , [] ) self.assertEqual(_A , [] ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) __a : Union[str, Any] = process_story(_A ) __a : Optional[int] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(_A , _A ) __a : str = ['It was the best of times.'] self.assertEqual(_A , _A ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = torch.tensor([1, 2, 3, 4] ) __a : Any = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(_A , 0 ).numpy() , expected.numpy() ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) __a : List[str] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_A , 23 ).numpy() , expected.numpy() ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) __a : Dict = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(_A , 1 ).numpy() , expected.numpy() ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = 101 __a : Tuple = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) __a : Any = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) __a : Tuple = compute_token_type_ids(_A , _A ) np.testing.assert_array_equal(_A , _A )
710
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase = 13 , _lowercase = 64 , _lowercase = 2 , _lowercase = 3 , _lowercase = 3 , _lowercase = True , _lowercase = True , _lowercase = 128 , _lowercase=[16, 32, 64, 128] , _lowercase = 7 , _lowercase = 4 , _lowercase = 37 , _lowercase = "gelu" , _lowercase = 0.1 , _lowercase = 0.1 , _lowercase = 10 , _lowercase = 0.02 , _lowercase = 2 , _lowercase = 1 , _lowercase = 128 , _lowercase = [2, 2, 2, 2] , _lowercase = 2 , _lowercase = 2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : int = image_size __a : Tuple = patch_size __a : str = num_channels __a : Union[str, Any] = is_training __a : List[Any] = use_labels __a : int = hidden_size __a : Optional[Any] = num_hidden_layers __a : List[Any] = num_attention_heads __a : Dict = intermediate_size __a : str = hidden_act __a : Dict = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Optional[int] = type_sequence_label_size __a : Dict = initializer_range __a : Dict = encoder_stride __a : int = num_attention_outputs __a : List[Any] = embed_dim __a : Optional[Any] = embed_dim + 1 __a : Optional[Any] = resolution __a : Optional[Any] = depths __a : Union[str, Any] = hidden_sizes __a : List[str] = dim __a : Any = mlp_expansion_ratio def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_labels: __a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowercase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = TFEfficientFormerModel(config=_lowercase ) __a : List[Any] = model(_lowercase , training=_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = self.type_sequence_label_size __a : Any = TFEfficientFormerForImageClassification(_lowercase ) __a : Union[str, Any] = model(_lowercase , labels=_lowercase , training=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a : Optional[Any] = 1 __a : int = TFEfficientFormerForImageClassification(_lowercase ) __a : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : str = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _lowerCAmelCase = ( { "feature-extraction": TFEfficientFormerModel, "image-classification": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = TFEfficientFormerModelTester(self ) __a : Any = ConfigTester( self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(_lowercase ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Union[str, Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : Tuple = model_class(_lowercase ) __a : int = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a : str = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_lowercase ) , _lowercase ) if hasattr(self.model_tester , """encoder_seq_length""" ): __a : Any = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: __a : int = seq_length * self.model_tester.chunk_length else: __a : Any = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __a : Optional[int] = outputs.decoder_hidden_states self.asseretIsInstance(_lowercase , (list, tuple) ) self.assertEqual(len(_lowercase ) , _lowercase ) __a : Any = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : List[Any] = getattr(self.model_tester , """decoder_seq_length""" , _lowercase ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : int = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' __a : Any = super()._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = TFEfficientFormerModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : int = True __a : Optional[int] = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """encoder_seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """key_length""" , _lowercase ) __a : int = getattr(self.model_tester , """chunk_length""" , _lowercase ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): __a : List[str] = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __a : List[Any] = True __a : Tuple = False __a : List[Any] = True __a : int = model_class(_lowercase ) __a : List[Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Dict = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a : Optional[Any] = True __a : List[str] = model_class(_lowercase ) __a : Dict = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : int = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __a : Dict = model_class(_lowercase ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __a : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=_lowercase ) for key, val in model.input_signature.items() if key in model.dummy_inputs } __a : Optional[Any] = model(_lowercase ) self.assertTrue(outputs_dict is not None ) def __magic_name__ ( ): __a : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : str = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) __a : Optional[Any] = self.default_image_processor __a : List[str] = prepare_img() __a : int = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : Optional[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : str = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : Dict = tf.constant([-0.0555, 0.4825, -0.0852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) __a : Any = self.default_image_processor __a : str = prepare_img() __a : str = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : List[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : int = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : List[str] = tf.constant([-0.1312, 0.4353, -1.0499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
63
0
"""simple docstring""" from math import asin, atan, cos, radians, sin, sqrt, tan lowercase__ = 6378137.0 lowercase__ = 6356752.314245 lowercase__ = 6378137 def __magic_name__ ( _lowerCamelCase : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : Any ): __a : List[str] = (AXIS_A - AXIS_B) / AXIS_A __a : Any = atan((1 - flattening) * tan(radians(__snake_case ) ) ) __a : Tuple = atan((1 - flattening) * tan(radians(__snake_case ) ) ) __a : Any = radians(__snake_case ) __a : Optional[int] = radians(__snake_case ) # Equation __a : List[str] = sin((phi_a - phi_a) / 2 ) __a : Any = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda __a : Optional[Any] = sqrt(sin_sq_phi + (cos(__snake_case ) * cos(__snake_case ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
711
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=0 ): '''simple docstring''' __a : Any = 1.0 if scale is None else scale __a : str = 0.0 if loc is None else loc super().__init__(_lowercase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=_lowercase )] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.variance.sqrt() class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' super().__init__(**_lowercase ) __a : str = args_dim __a : List[Any] = nn.ModuleList([nn.Linear(_lowercase , _lowercase ) for dim in args_dim.values()] ) __a : Dict = domain_map def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[Any] = [proj(_lowercase ) for proj in self.proj] return self.domain_map(*_lowercase ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__() __a : Optional[int] = function def lowerCAmelCase__(self , _lowercase , *_lowercase ): '''simple docstring''' return self.function(_lowercase , *_lowercase ) class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 42 _lowerCAmelCase = 42 _lowerCAmelCase = 42 def __init__(self , _lowercase = 1 ): '''simple docstring''' __a : Optional[int] = dim __a : str = {k: dim * self.args_dim[k] for k in self.args_dim} def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if self.dim == 1: return self.distribution_class(*_lowercase ) else: return Independent(self.distribution_class(*_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , ): '''simple docstring''' __a : Tuple = self._base_distribution(_lowercase ) if loc is None and scale is None: return distr else: return AffineTransformed(_lowercase , loc=_lowercase , scale=_lowercase , event_dim=self.event_dim ) @property def lowerCAmelCase__(self ): '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.event_shape ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 0.0 def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return ParameterProjection( in_features=_lowercase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def lowerCAmelCase__(self , *_lowercase ): '''simple docstring''' raise NotImplementedError() @staticmethod def lowerCAmelCase__(_lowercase ): '''simple docstring''' return (x + torch.sqrt(torch.square(_lowercase ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"df": 1, "loc": 1, "scale": 1} _lowerCAmelCase = StudentT @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) __a : Optional[Any] = 2.0 + cls.squareplus(_lowercase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"loc": 1, "scale": 1} _lowerCAmelCase = Normal @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : str = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"total_count": 1, "logits": 1} _lowerCAmelCase = NegativeBinomial @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = cls.squareplus(_lowercase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a , __a : Optional[Any] = distr_args if self.dim == 1: return self.distribution_class(total_count=_lowercase , logits=_lowercase ) else: return Independent(self.distribution_class(total_count=_lowercase , logits=_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None ): '''simple docstring''' __a , __a : List[Any] = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
63
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer lowercase__ = logging.get_logger(__name__) lowercase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } lowercase__ = { "google/realm-cc-news-pretrained-embedder": 512, "google/realm-cc-news-pretrained-encoder": 512, "google/realm-cc-news-pretrained-scorer": 512, "google/realm-cc-news-pretrained-openqa": 512, "google/realm-orqa-nq-openqa": 512, "google/realm-orqa-nq-reader": 512, "google/realm-orqa-wq-openqa": 512, "google/realm-orqa-wq-reader": 512, } lowercase__ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class SCREAMING_SNAKE_CASE__ ( lowercase_ ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = RealmTokenizer def __init__(self , _lowercase=None , _lowercase=None , _lowercase=True , _lowercase="[UNK]" , _lowercase="[SEP]" , _lowercase="[PAD]" , _lowercase="[CLS]" , _lowercase="[MASK]" , _lowercase=True , _lowercase=None , **_lowercase , ): '''simple docstring''' super().__init__( lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , do_lower_case=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , tokenize_chinese_chars=lowerCamelCase_ , strip_accents=lowerCamelCase_ , **lowerCamelCase_ , ) __a : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowerCamelCase_ ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowerCamelCase_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowerCamelCase_ ) != tokenize_chinese_chars ): __a : Optional[int] = getattr(lowerCamelCase_ , normalizer_state.pop("""type""" ) ) __a : Dict = do_lower_case __a : Tuple = strip_accents __a : Optional[Any] = tokenize_chinese_chars __a : Optional[Any] = normalizer_class(**lowerCamelCase_ ) __a : List[Any] = do_lower_case def lowerCAmelCase__(self , _lowercase , **_lowercase ): '''simple docstring''' __a : Tuple = PaddingStrategy.MAX_LENGTH __a : int = text __a : Optional[int] = kwargs.pop("""text_pair""" , lowerCamelCase_ ) __a : Dict = kwargs.pop("""return_tensors""" , lowerCamelCase_ ) __a : str = { """input_ids""": [], """attention_mask""": [], """token_type_ids""": [], } for idx, candidate_text in enumerate(lowerCamelCase_ ): if batch_text_pair is not None: __a : Tuple = batch_text_pair[idx] else: __a : int = None __a : Union[str, Any] = super().__call__(lowerCamelCase_ , lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) __a : List[str] = encoded_candidates.get("""input_ids""" ) __a : int = encoded_candidates.get("""attention_mask""" ) __a : Any = encoded_candidates.get("""token_type_ids""" ) if encoded_input_ids is not None: output_data["input_ids"].append(lowerCamelCase_ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(lowerCamelCase_ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(lowerCamelCase_ ) __a : Optional[Any] = {key: item for key, item in output_data.items() if len(lowerCamelCase_ ) != 0} return BatchEncoding(lowerCamelCase_ , tensor_type=lowerCamelCase_ ) def lowerCAmelCase__(self , _lowercase , _lowercase=None ): '''simple docstring''' __a : str = [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 , _lowercase , _lowercase = None ): '''simple docstring''' __a : Union[str, Any] = [self.sep_token_id] __a : 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 , _lowercase , _lowercase = None ): '''simple docstring''' __a : Union[str, Any] = self._tokenizer.model.save(lowerCamelCase_ , name=lowerCamelCase_ ) return tuple(lowerCamelCase_ )
712
"""simple docstring""" import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = KandinskyVaaPriorPipeline _lowerCAmelCase = ["prompt"] _lowerCAmelCase = ["prompt", "negative_prompt"] _lowerCAmelCase = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] _lowerCAmelCase = False @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim * 4 @property def lowerCAmelCase__(self ): '''simple docstring''' return 100 @property def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_lowercase ) @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : Dict = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a : Tuple = PriorTransformer(**_lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a : int = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[str] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a : Optional[Any] = CLIPVisionModelWithProjection(_lowercase ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = CLIPImageProcessor( crop_size=224 , do_center_crop=_lowercase , do_normalize=_lowercase , do_resize=_lowercase , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.dummy_prior __a : int = self.dummy_image_encoder __a : Any = self.dummy_text_encoder __a : int = self.dummy_tokenizer __a : Optional[Any] = self.dummy_image_processor __a : List[Any] = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=_lowercase , clip_sample_range=10.0 , ) __a : List[Any] = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def lowerCAmelCase__(self , _lowercase , _lowercase=0 ): '''simple docstring''' if str(_lowercase ).startswith("""mps""" ): __a : Dict = torch.manual_seed(_lowercase ) else: __a : Union[str, Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a : Union[str, Any] = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = """cpu""" __a : Union[str, Any] = self.get_dummy_components() __a : Dict = self.pipeline_class(**_lowercase ) __a : Tuple = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = pipe(**self.get_dummy_inputs(_lowercase ) ) __a : str = output.image_embeds __a : Any = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] __a : List[Any] = image[0, -10:] __a : List[Any] = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a : Optional[Any] = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = torch_device == """cpu""" __a : Any = True __a : Any = False self._test_inference_batch_single_identical( test_max_difference=_lowercase , relax_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , ) @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = torch_device == """cpu""" __a : Union[str, Any] = False self._test_attention_slicing_forward_pass( test_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , )
63
0
"""simple docstring""" import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder lowercase__ : Optional[int] = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase__ : Tuple = 256 class SCREAMING_SNAKE_CASE__ ( __lowerCamelCase ): _lowerCAmelCase = ['melgan'] def __init__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' super().__init__() # From MELGAN __a : Union[str, Any] = math.log(1e-5 ) # Matches MelGAN training. __a : str = 4.0 # Largest value for most examples __a : List[Any] = 128 self.register_modules( notes_encoder=UpperCamelCase_ , continuous_encoder=UpperCamelCase_ , decoder=UpperCamelCase_ , scheduler=UpperCamelCase_ , melgan=UpperCamelCase_ , ) def lowerCAmelCase__(self , _lowercase , _lowercase=(-1.0, 1.0) , _lowercase=False ): '''simple docstring''' __a , __a : List[str] = output_range if clip: __a : str = torch.clip(UpperCamelCase_ , self.min_value , self.max_value ) # Scale to [0, 1]. __a : int = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def lowerCAmelCase__(self , _lowercase , _lowercase=(-1.0, 1.0) , _lowercase=False ): '''simple docstring''' __a , __a : str = input_range __a : Tuple = torch.clip(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if clip else outputs # Scale to [0, 1]. __a : int = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = input_tokens > 0 __a , __a : List[str] = self.notes_encoder( encoder_input_tokens=UpperCamelCase_ , encoder_inputs_mask=UpperCamelCase_ ) __a , __a : List[str] = self.continuous_encoder( encoder_inputs=UpperCamelCase_ , encoder_inputs_mask=UpperCamelCase_ ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = noise_time if not torch.is_tensor(UpperCamelCase_ ): __a : Any = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(UpperCamelCase_ ) and len(timesteps.shape ) == 0: __a : List[str] = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __a : List[Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) __a : str = self.decoder( encodings_and_masks=UpperCamelCase_ , decoder_input_tokens=UpperCamelCase_ , decoder_noise_time=UpperCamelCase_ ) return logits @torch.no_grad() def __call__(self , _lowercase , _lowercase = None , _lowercase = 100 , _lowercase = True , _lowercase = "numpy" , _lowercase = None , _lowercase = 1 , ): '''simple docstring''' if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(UpperCamelCase_ )}.''' ) __a : List[Any] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) __a : Optional[Any] = np.zeros([1, 0, self.n_dims] , np.floataa ) __a : Dict = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase_ , device=self.device ) for i, encoder_input_tokens in enumerate(UpperCamelCase_ ): if i == 0: __a : Dict = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. __a : int = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase_ , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. __a : Any = ones __a : Optional[int] = self.scale_features( UpperCamelCase_ , output_range=[-1.0, 1.0] , clip=UpperCamelCase_ ) __a : Tuple = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=UpperCamelCase_ , continuous_mask=UpperCamelCase_ , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop __a : List[Any] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=UpperCamelCase_ , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(UpperCamelCase_ ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __a : str = self.decode( encodings_and_masks=UpperCamelCase_ , input_tokens=UpperCamelCase_ , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 __a : Optional[int] = self.scheduler.step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ ).prev_sample __a : List[str] = self.scale_to_features(UpperCamelCase_ , input_range=[-1.0, 1.0] ) __a : str = mel[:1] __a : List[str] = mel.cpu().float().numpy() __a : Optional[Any] = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCamelCase_ , UpperCamelCase_ ) logger.info("""Generated segment""" , UpperCamelCase_ ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( """Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" ) elif output_type == "numpy" and self.melgan is None: raise ValueError( """Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" ) if output_type == "numpy": __a : int = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: __a : Optional[Any] = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=UpperCamelCase_ )
713
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = LEDTokenizer _lowerCAmelCase = LEDTokenizerFast _lowerCAmelCase = True def lowerCAmelCase__(self ): '''simple docstring''' super().setUp() __a : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __a : int = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) __a : Optional[int] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __a : List[Any] = {"""unk_token""": """<unk>"""} __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_lowercase ) ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] __a : List[str] = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer(_lowercase , max_length=len(_lowercase ) , padding=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __a : Dict = batch.input_ids.tolist()[0] self.assertListEqual(_lowercase , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Tuple = tokenizer(_lowercase , padding=_lowercase , return_tensors="""pt""" ) self.assertIn("""input_ids""" , _lowercase ) self.assertIn("""attention_mask""" , _lowercase ) self.assertNotIn("""labels""" , _lowercase ) self.assertNotIn("""decoder_attention_mask""" , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Dict = tokenizer(text_target=_lowercase , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer( ["""I am a small frog""" * 1024, """I am a small frog"""] , padding=_lowercase , truncation=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = ["""A long paragraph for summarization."""] __a : Dict = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : int = tokenizer(_lowercase , return_tensors="""pt""" ) __a : Dict = tokenizer(text_target=_lowercase , return_tensors="""pt""" ) __a : List[str] = inputs["""input_ids"""] __a : List[Any] = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[Any] = ["""Summary of the text.""", """Another summary."""] __a : List[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a : Union[str, Any] = tokenizer(_lowercase , padding=_lowercase ) __a : Tuple = [[0] * len(_lowercase ) for x in encoded_output["""input_ids"""]] __a : Union[str, Any] = tokenizer.pad(_lowercase ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __a : Dict = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = """A, <mask> AllenNLP sentence.""" __a : Dict = tokenizer_r.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) __a : Tuple = tokenizer_p.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) __a : Tuple = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) __a : Any = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
63
0
"""simple docstring""" lowercase__ = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} lowercase__ = ["a", "b", "c", "d", "e"] def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : int , _lowerCamelCase : Dict ): __a : List[str] = start # add current to visited visited.append(lowerCamelCase__ ) __a : Optional[int] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __a : int = topological_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # if all neighbors visited add current to sort sort.append(lowerCamelCase__ ) # if all vertices haven't been visited select a new one to visit if len(lowerCamelCase__ ) != len(lowerCamelCase__ ): for vertice in vertices: if vertice not in visited: __a : Tuple = topological_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # return sort return sort if __name__ == "__main__": lowercase__ = topological_sort("a", [], []) print(sort)
714
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=512, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def __magic_name__ ( _lowerCamelCase : Optional[Any] ): if string == "True": return True elif string == "False": return False else: raise ValueError(F'''could not parse string as bool {string}''' ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) lowercase__ = parser.parse_args() lowercase__ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : Optional[Any] ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __magic_name__ ( _lowerCamelCase : List[Any] ): __a : Union[str, Any] = 0 __a : Optional[Any] = number while duplicate > 0: __a , __a : Dict = divmod(a__ , 1_0 ) fact_sum += factorial(a__ ) return fact_sum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") lowercase__ = int(input("Enter number: ").strip()) print( f'{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.' )
715
"""simple docstring""" import torch from diffusers import DiffusionPipeline class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase ): '''simple docstring''' super().__init__() self.register_modules(unet=_lowercase , scheduler=_lowercase ) def __call__(self ): '''simple docstring''' __a : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __a : Optional[Any] = 1 __a : List[str] = self.unet(_lowercase , _lowercase ).sample __a : Union[str, Any] = self.scheduler.step(_lowercase , _lowercase , _lowercase ).prev_sample __a : Optional[int] = scheduler_output - scheduler_output + torch.ones_like(_lowercase ) return result
63
0
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowercase__ = False lowercase__ = logging.get_logger(__name__) lowercase__ = "ybelkada/fonts" def __magic_name__ ( ): if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' """Pix2StructImageProcessor. Please upgrade torch.""" ) def __magic_name__ ( _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Optional[int] ): requires_backends(snake_case__ , ["""torch"""] ) _check_torch_version() __a : Optional[int] = image_tensor.unsqueeze(0 ) __a : Optional[Any] = torch.nn.functional.unfold(snake_case__ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) __a : List[str] = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , snake_case__ , snake_case__ , -1 ) __a : int = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : int = 3_6 , _lowerCamelCase : str = "black" , _lowerCamelCase : str = "white" , _lowerCamelCase : int = 5 , _lowerCamelCase : int = 5 , _lowerCamelCase : int = 5 , _lowerCamelCase : int = 5 , _lowerCamelCase : Optional[bytes] = None , _lowerCamelCase : Optional[str] = None , ): requires_backends(snake_case__ , """vision""" ) # Add new lines so that each line is no more than 80 characters. __a : Any = textwrap.TextWrapper(width=8_0 ) __a : Union[str, Any] = wrapper.wrap(text=snake_case__ ) __a : Tuple = """\n""".join(snake_case__ ) if font_bytes is not None and font_path is None: __a : List[Any] = io.BytesIO(snake_case__ ) elif font_path is not None: __a : Any = font_path else: __a : int = hf_hub_download(snake_case__ , """Arial.TTF""" ) __a : Optional[Any] = ImageFont.truetype(snake_case__ , encoding="""UTF-8""" , size=snake_case__ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. __a : Union[str, Any] = ImageDraw.Draw(Image.new("""RGB""" , (1, 1) , snake_case__ ) ) __a , __a , __a , __a : List[str] = temp_draw.textbbox((0, 0) , snake_case__ , snake_case__ ) # Create the actual image with a bit of padding around the text. __a : Dict = text_width + left_padding + right_padding __a : Union[str, Any] = text_height + top_padding + bottom_padding __a : Dict = Image.new("""RGB""" , (image_width, image_height) , snake_case__ ) __a : Union[str, Any] = ImageDraw.Draw(snake_case__ ) draw.text(xy=(left_padding, top_padding) , text=snake_case__ , fill=snake_case__ , font=snake_case__ ) return image def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : str , **_lowerCamelCase : List[str] ): requires_backends(snake_case__ , """vision""" ) # Convert to PIL image if necessary __a : str = to_pil_image(snake_case__ ) __a : Optional[Any] = render_text(snake_case__ , **snake_case__ ) __a : List[str] = max(header_image.width , image.width ) __a : List[str] = int(image.height * (new_width / image.width) ) __a : Optional[Any] = int(header_image.height * (new_width / header_image.width) ) __a : str = Image.new("""RGB""" , (new_width, new_height + new_header_height) , """white""" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary __a : Union[str, Any] = to_numpy_array(snake_case__ ) if infer_channel_dimension_format(snake_case__ ) == ChannelDimension.LAST: __a : Union[str, Any] = to_channel_dimension_format(snake_case__ , ChannelDimension.LAST ) return new_image class SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase ): _lowerCAmelCase = ['''flattened_patches'''] def __init__(self , _lowercase = True , _lowercase = True , _lowercase = None , _lowercase = 2048 , _lowercase = False , **_lowercase , ): '''simple docstring''' super().__init__(**lowerCAmelCase_ ) __a : Tuple = patch_size if patch_size is not None else {"""height""": 16, """width""": 16} __a : Tuple = do_normalize __a : List[Any] = do_convert_rgb __a : Optional[Any] = max_patches __a : Any = is_vqa def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' requires_backends(self.extract_flattened_patches , """torch""" ) _check_torch_version() # convert to torch __a : int = to_channel_dimension_format(lowerCAmelCase_ , ChannelDimension.FIRST ) __a : Union[str, Any] = torch.from_numpy(lowerCAmelCase_ ) __a , __a : Optional[int] = patch_size["""height"""], patch_size["""width"""] __a , __a : str = get_image_size(lowerCAmelCase_ ) # maximize scale s.t. __a : Dict = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) __a : List[str] = max(min(math.floor(scale * image_height / patch_height ) , lowerCAmelCase_ ) , 1 ) __a : Optional[Any] = max(min(math.floor(scale * image_width / patch_width ) , lowerCAmelCase_ ) , 1 ) __a : List[str] = max(num_feasible_rows * patch_height , 1 ) __a : List[str] = max(num_feasible_cols * patch_width , 1 ) __a : Optional[Any] = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="""bilinear""" , align_corners=lowerCAmelCase_ , antialias=lowerCAmelCase_ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] __a : Tuple = torch_extract_patches(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __a : Tuple = patches.shape __a : Tuple = patches_shape[1] __a : Union[str, Any] = patches_shape[2] __a : Optional[int] = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] __a : Tuple = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] __a : Dict = torch.arange(lowerCAmelCase_ ).reshape([rows, 1] ).repeat(1 , lowerCAmelCase_ ).reshape([rows * columns, 1] ) __a : Any = torch.arange(lowerCAmelCase_ ).reshape([1, columns] ).repeat(lowerCAmelCase_ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] __a : Union[str, Any] = row_ids.to(torch.floataa ) __a : Union[str, Any] = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] __a : Dict = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] __a : Optional[Any] = torch.nn.functional.pad(lowerCAmelCase_ , [0, 0, 0, max_patches - (rows * columns)] ).float() __a : Optional[int] = to_numpy_array(lowerCAmelCase_ ) return result def lowerCAmelCase__(self , _lowercase , _lowercase = None , **_lowercase ): '''simple docstring''' if image.dtype == np.uinta: __a : List[str] = image.astype(np.floataa ) # take mean across the whole `image` __a : Optional[int] = np.mean(lowerCAmelCase_ ) __a : Dict = np.std(lowerCAmelCase_ ) __a : List[Any] = max(lowerCAmelCase_ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(lowerCAmelCase_ , mean=lowerCAmelCase_ , std=lowerCAmelCase_ , **lowerCAmelCase_ ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = ChannelDimension.FIRST , **_lowercase , ): '''simple docstring''' __a : Any = do_normalize if do_normalize is not None else self.do_normalize __a : str = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __a : str = patch_size if patch_size is not None else self.patch_size __a : str = max_patches if max_patches is not None else self.max_patches __a : Dict = self.is_vqa if kwargs.get("""data_format""" , lowerCAmelCase_ ) is not None: raise ValueError("""data_format is not an accepted input as the outputs are """ ) __a : Dict = make_list_of_images(lowerCAmelCase_ ) if not valid_images(lowerCAmelCase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: __a : Optional[int] = [convert_to_rgb(lowerCAmelCase_ ) for image in images] # All transformations expect numpy arrays. __a : Optional[Any] = [to_numpy_array(lowerCAmelCase_ ) for image in images] if is_vqa: if header_text is None: raise ValueError("""A header text must be provided for VQA models.""" ) __a : Tuple = kwargs.pop("""font_bytes""" , lowerCAmelCase_ ) __a : int = kwargs.pop("""font_path""" , lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): __a : Optional[int] = [header_text] * len(lowerCAmelCase_ ) __a : List[Any] = [ render_header(lowerCAmelCase_ , header_text[i] , font_bytes=lowerCAmelCase_ , font_path=lowerCAmelCase_ ) for i, image in enumerate(lowerCAmelCase_ ) ] if do_normalize: __a : Tuple = [self.normalize(image=lowerCAmelCase_ ) for image in images] # convert to torch tensor and permute __a : Optional[int] = [ self.extract_flattened_patches(image=lowerCAmelCase_ , max_patches=lowerCAmelCase_ , patch_size=lowerCAmelCase_ ) for image in images ] # create attention mask in numpy __a : Optional[int] = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] __a : Any = BatchFeature( data={"""flattened_patches""": images, """attention_mask""": attention_masks} , tensor_type=lowerCAmelCase_ ) return encoded_outputs
716
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json", # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "vit_msn" def __init__(self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1e-06 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=True , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase ) __a : int = hidden_size __a : str = num_hidden_layers __a : str = num_attention_heads __a : Optional[Any] = intermediate_size __a : Union[str, Any] = hidden_act __a : Tuple = hidden_dropout_prob __a : Any = attention_probs_dropout_prob __a : List[Any] = initializer_range __a : Any = layer_norm_eps __a : Dict = image_size __a : List[Any] = patch_size __a : Dict = num_channels __a : Optional[Any] = qkv_bias
63
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = LDMTextToImagePipeline _lowerCAmelCase = TEXT_TO_IMAGE_PARAMS - { 'negative_prompt', 'negative_prompt_embeds', 'cross_attention_kwargs', 'prompt_embeds', } _lowerCAmelCase = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'callback', 'callback_steps', } _lowerCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __a : int = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=UpperCAmelCase__ , set_alpha_to_one=UpperCAmelCase__ , ) torch.manual_seed(0 ) __a : List[Any] = AutoencoderKL( block_out_channels=(32, 64) , in_channels=3 , out_channels=3 , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , latent_channels=4 , ) torch.manual_seed(0 ) __a : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __a : Tuple = CLIPTextModel(UpperCAmelCase__ ) __a : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __a : Tuple = { '''unet''': unet, '''scheduler''': scheduler, '''vqvae''': vae, '''bert''': text_encoder, '''tokenizer''': tokenizer, } return components def lowerCAmelCase__(self , _lowercase , _lowercase=0 ): '''simple docstring''' if str(UpperCAmelCase__ ).startswith("""mps""" ): __a : List[Any] = torch.manual_seed(UpperCAmelCase__ ) else: __a : Optional[Any] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __a : Optional[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator __a : Optional[Any] = self.get_dummy_components() __a : Optional[Any] = LDMTextToImagePipeline(**UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __a : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) __a : Tuple = pipe(**UpperCAmelCase__ ).images __a : int = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) __a : Union[str, Any] = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__(self , _lowercase , _lowercase=torch.floataa , _lowercase=0 ): '''simple docstring''' __a : Any = torch.manual_seed(UpperCAmelCase__ ) __a : str = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 32, 32) ) __a : str = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) __a : Optional[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : int = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __a : Any = self.get_inputs(UpperCAmelCase__ ) __a : Dict = pipe(**UpperCAmelCase__ ).images __a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) __a : List[Any] = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878] ) __a : str = np.abs(expected_slice - image_slice ).max() assert max_diff < 1e-3 @nightly @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__(self , _lowercase , _lowercase=torch.floataa , _lowercase=0 ): '''simple docstring''' __a : Tuple = torch.manual_seed(UpperCAmelCase__ ) __a : List[Any] = np.random.RandomState(UpperCAmelCase__ ).standard_normal((1, 4, 32, 32) ) __a : str = torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) __a : Optional[int] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 50, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __a : List[Any] = self.get_inputs(UpperCAmelCase__ ) __a : List[str] = pipe(**UpperCAmelCase__ ).images[0] __a : str = load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" ) __a : Any = np.abs(expected_image - image ).max() assert max_diff < 1e-3
717
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowercase__ = logging.get_logger(__name__) lowercase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRContextEncoderTokenizer class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRQuestionEncoderTokenizer lowercase__ = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) lowercase__ = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) lowercase__ = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ : def __call__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , **_lowercase , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) elif titles is None or texts is None: __a : str = titles if texts is None else texts return super().__call__( _lowercase , _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) __a : str = titles if not isinstance(_lowercase , _lowercase ) else [titles] __a : Optional[Any] = texts if not isinstance(_lowercase , _lowercase ) else [texts] __a : Tuple = len(_lowercase ) __a : Dict = questions if not isinstance(_lowercase , _lowercase ) else [questions] * n_passages assert len(_lowercase ) == len( _lowercase ), F'''There should be as many titles than texts but got {len(_lowercase )} titles and {len(_lowercase )} texts.''' __a : Optional[Any] = super().__call__(_lowercase , _lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : str = super().__call__(_lowercase , add_special_tokens=_lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : Union[str, Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowercase , _lowercase ) ] } if return_attention_mask is not False: __a : Optional[int] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __a : str = attention_mask return self.pad(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 16 , _lowercase = 64 , _lowercase = 4 , ): '''simple docstring''' __a : Union[str, Any] = reader_input["""input_ids"""] __a , __a , __a : Optional[int] = reader_output[:3] __a : int = len(_lowercase ) __a : Any = sorted(range(_lowercase ) , reverse=_lowercase , key=relevance_logits.__getitem__ ) __a : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __a : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __a : Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __a : int = sequence_ids.index(self.pad_token_id ) else: __a : Optional[Any] = len(_lowercase ) __a : List[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowercase , top_spans=_lowercase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowercase , start_index=_lowercase , end_index=_lowercase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowercase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' __a : Tuple = [] for start_index, start_score in enumerate(_lowercase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __a : str = sorted(_lowercase , key=lambda _lowercase : x[1] , reverse=_lowercase ) __a : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' __a : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowercase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = ["input_ids", "attention_mask"] _lowerCAmelCase = DPRReaderTokenizer
63
0
"""simple docstring""" import os import pytest from attr import dataclass lowercase__ = """us-east-1""" # defaults region @dataclass class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 4_2 _lowerCAmelCase = "arn:aws:iam::558105141721:role/sagemaker_execution_role" _lowerCAmelCase = { "task_name": "mnli", "per_device_train_batch_size": 1_6, "per_device_eval_batch_size": 1_6, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 5_0_0, "save_steps": 5_5_0_0, } _lowerCAmelCase = {**hyperparameters, "max_steps": 1_0_0_0} @property def lowerCAmelCase__(self ): '''simple docstring''' if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def lowerCAmelCase__(self ): '''simple docstring''' return F'''{self.framework}-transfromers-test''' @property def lowerCAmelCase__(self ): '''simple docstring''' return F'''./tests/sagemaker/scripts/{self.framework}''' @property def lowerCAmelCase__(self ): '''simple docstring''' if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="""class""" ) def __magic_name__ ( _lowerCamelCase : List[str] ): __a : Tuple = SageMakerTestEnvironment(framework=request.cls.framework )
718
"""simple docstring""" import os def __magic_name__ ( _lowerCamelCase : Dict ): __a : List[str] = len(grid[0] ) __a : int = len(_lowerCamelCase ) __a : Tuple = 0 __a : List[Any] = 0 __a : List[str] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_lowerCamelCase ): for j in range(n_rows - 3 ): __a : List[Any] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] __a : Tuple = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: __a : List[Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: __a : List[Any] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) __a : str = max( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if max_product > largest: __a : Optional[Any] = max_product return largest def __magic_name__ ( ): __a : Tuple = [] with open(os.path.dirname(_lowerCamelCase ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) __a : Tuple = [[int(_lowerCamelCase ) for i in grid[j]] for j in range(len(_lowerCamelCase ) )] return largest_product(_lowerCamelCase ) if __name__ == "__main__": print(solution())
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : Optional[Any] ): __a : int = [0] * len(__a ) __a : Optional[int] = [] __a : List[str] = [1] * len(__a ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__a ) ): if indegree[i] == 0: queue.append(__a ) while queue: __a : Any = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __a : str = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__a ) print(max(__a ) ) # Adjacency list of Graph lowercase__ = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
719
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 42 _lowerCAmelCase = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
63
0
"""simple docstring""" import colorsys from PIL import Image # type: ignore def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int ): __a : Any = x __a : int = y for step in range(_lowerCamelCase ): # noqa: B007 __a : str = a * a - b * b + x __a : Tuple = 2 * a * b + y __a : List[Any] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def __magic_name__ ( _lowerCamelCase : float ): if distance == 1: return (0, 0, 0) else: return (2_5_5, 2_5_5, 2_5_5) def __magic_name__ ( _lowerCamelCase : float ): if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_5_5 ) for i in colorsys.hsv_to_rgb(_lowerCamelCase , 1 , 1 ) ) def __magic_name__ ( _lowerCamelCase : int = 8_0_0 , _lowerCamelCase : int = 6_0_0 , _lowerCamelCase : float = -0.6 , _lowerCamelCase : float = 0 , _lowerCamelCase : float = 3.2 , _lowerCamelCase : int = 5_0 , _lowerCamelCase : bool = True , ): __a : Any = Image.new("""RGB""" , (image_width, image_height) ) __a : str = img.load() # loop through the image-coordinates for image_x in range(_lowerCamelCase ): for image_y in range(_lowerCamelCase ): # determine the figure-coordinates based on the image-coordinates __a : str = figure_width / image_width * image_height __a : Dict = figure_center_x + (image_x / image_width - 0.5) * figure_width __a : Union[str, Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __a : List[str] = get_distance(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __a : Tuple = get_color_coded_rgb(_lowerCamelCase ) else: __a : List[str] = get_black_and_white_rgb(_lowerCamelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowercase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
720
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _lowerCAmelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCAmelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowerCAmelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowerCAmelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Optional[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __a : int = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : List[str] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __a : Optional[int] = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Tuple = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __a : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : Union[str, Any] = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __a : Optional[int] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __a : List[str] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = pipeline("""text-classification""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : Union[str, Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = pipeline("""text-classification""" , framework="""tf""" ) __a : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Tuple = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = TextClassificationPipeline(model=_lowercase , tokenizer=_lowercase ) return text_classifier, ["HuggingFace is in", "This is another test"] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __a : Union[str, Any] = """HuggingFace is in""" __a : List[str] = text_classifier(_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __a : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __a : Dict = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}, {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __a : Dict = text_classifier(_lowercase , top_k=_lowercase ) __a : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N, [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N] , ) __a : Dict = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __a : Any = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __a : Dict = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(_lowercase ): text_classifier(_lowercase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __a : Optional[int] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
63
0
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase=2 , _lowercase=True , _lowercase=False , _lowercase=10 , _lowercase=3 , _lowercase=32 * 8 , _lowercase=32 * 8 , _lowercase=4 , _lowercase=64 , ): '''simple docstring''' __a : List[Any] = parent __a : Optional[int] = batch_size __a : Optional[int] = is_training __a : str = use_auxiliary_loss __a : int = num_queries __a : Dict = num_channels __a : str = min_size __a : Optional[int] = max_size __a : Any = num_labels __a : Any = hidden_dim __a : List[Any] = hidden_dim def lowerCAmelCase__(self ): '''simple docstring''' __a : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( UpperCAmelCase__ ) __a : str = torch.ones([self.batch_size, self.min_size, self.max_size] , device=UpperCAmelCase__ ) __a : List[str] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=UpperCAmelCase__ ) > 0.5 ).float() __a : Any = (torch.rand((self.batch_size, self.num_labels) , device=UpperCAmelCase__ ) > 0.5).long() __a : Tuple = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCAmelCase__(self ): '''simple docstring''' __a : str = MaskaFormerConfig( hidden_size=self.hidden_dim , ) __a : List[str] = self.num_queries __a : Tuple = self.num_labels __a : Tuple = [1, 1, 1, 1] __a : Tuple = self.num_channels __a : Any = 64 __a : List[Any] = 128 __a : Union[str, Any] = self.hidden_dim __a : str = self.hidden_dim __a : Dict = self.hidden_dim return config def lowerCAmelCase__(self ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() __a : List[str] = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : str = output.encoder_hidden_states __a : Optional[Any] = output.pixel_decoder_hidden_states __a : List[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(UpperCAmelCase__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) , config.decoder_layers ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' with torch.no_grad(): __a : int = MaskaFormerModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __a : List[Any] = model(pixel_values=UpperCAmelCase__ , pixel_mask=UpperCAmelCase__ ) __a : Dict = model(UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = MaskaFormerForUniversalSegmentation(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() def comm_check_on_output(_lowercase ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __a : Optional[Any] = model(pixel_values=UpperCAmelCase__ , pixel_mask=UpperCAmelCase__ ) __a : List[Any] = model(UpperCAmelCase__ ) comm_check_on_output(UpperCAmelCase__ ) __a : str = model( pixel_values=UpperCAmelCase__ , pixel_mask=UpperCAmelCase__ , mask_labels=UpperCAmelCase__ , class_labels=UpperCAmelCase__ ) comm_check_on_output(UpperCAmelCase__ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , unittest.TestCase ): _lowerCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () _lowerCAmelCase = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = MaskaFormerModelTester(self ) __a : Optional[Any] = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(UpperCAmelCase__ , **UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*UpperCAmelCase__ ) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Tuple = model_class(UpperCAmelCase__ ) __a : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : List[str] = [*signature.parameters.keys()] __a : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: __a : Dict = MaskaFormerModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = (self.model_tester.min_size,) * 2 __a : int = { '''pixel_values''': torch.randn((2, 3, *size) , device=UpperCAmelCase__ ), '''mask_labels''': torch.randn((2, 10, *size) , device=UpperCAmelCase__ ), '''class_labels''': torch.zeros(2 , 10 , device=UpperCAmelCase__ ).long(), } __a : Tuple = self.model_tester.get_config() __a : List[Any] = MaskaFormerForUniversalSegmentation(UpperCAmelCase__ ).to(UpperCAmelCase__ ) __a : List[str] = model(**UpperCAmelCase__ ) self.assertTrue(outputs.loss is not None ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(UpperCAmelCase__ , **UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(UpperCAmelCase__ ).to(UpperCAmelCase__ ) __a : Any = model(**UpperCAmelCase__ , output_attentions=UpperCAmelCase__ ) self.assertTrue(outputs.attentions is not None ) def lowerCAmelCase__(self ): '''simple docstring''' if not self.model_tester.is_training: return __a : Optional[Any] = self.all_model_classes[1] __a : Dict = self.model_tester.prepare_config_and_inputs() __a : str = model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.train() __a : Union[str, Any] = model(UpperCAmelCase__ , mask_labels=UpperCAmelCase__ , class_labels=UpperCAmelCase__ ).loss loss.backward() def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.all_model_classes[1] __a : Dict = self.model_tester.prepare_config_and_inputs() __a : str = True __a : Tuple = True __a : Union[str, Any] = model_class(UpperCAmelCase__ ).to(UpperCAmelCase__ ) model.train() __a : int = model(UpperCAmelCase__ , mask_labels=UpperCAmelCase__ , class_labels=UpperCAmelCase__ ) __a : Optional[Any] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __a : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() __a : Optional[Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __a : Dict = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=UpperCAmelCase__ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) lowercase__ = 1e-4 def __magic_name__ ( ): __a : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def lowerCAmelCase__(self ): '''simple docstring''' __a : int = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(UpperCAmelCase__ ) __a : Dict = self.default_image_processor __a : Optional[int] = prepare_img() __a : Any = image_processor(UpperCAmelCase__ , return_tensors="""pt""" ).to(UpperCAmelCase__ ) __a : Optional[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCAmelCase__ , (1, 3, 384, 384) ) with torch.no_grad(): __a : Union[str, Any] = model(**UpperCAmelCase__ ) __a : List[Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(UpperCAmelCase__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__ ) ) __a : Optional[int] = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(UpperCAmelCase__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__ ) ) __a : int = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(UpperCAmelCase__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__ ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(UpperCAmelCase__ ).eval() __a : str = self.default_image_processor __a : str = prepare_img() __a : Tuple = image_processor(UpperCAmelCase__ , return_tensors="""pt""" ).to(UpperCAmelCase__ ) __a : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(UpperCAmelCase__ , (1, 3, 384, 384) ) with torch.no_grad(): __a : Optional[Any] = model(**UpperCAmelCase__ ) # masks_queries_logits __a : List[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) __a : List[Any] = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] __a : Union[str, Any] = torch.tensor(UpperCAmelCase__ ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__ ) ) # class_queries_logits __a : Dict = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) __a : Optional[Any] = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__ ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(UpperCAmelCase__ ).eval() __a : int = self.default_image_processor __a : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="""pt""" , ) __a : Tuple = inputs['''pixel_values'''].to(UpperCAmelCase__ ) __a : Dict = [el.to(UpperCAmelCase__ ) for el in inputs['''mask_labels''']] __a : Union[str, Any] = [el.to(UpperCAmelCase__ ) for el in inputs['''class_labels''']] with torch.no_grad(): __a : List[str] = model(**UpperCAmelCase__ ) self.assertTrue(outputs.loss is not None )
721
"""simple docstring""" import unittest from knapsack import knapsack as k class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : str = 0 __a : Optional[Any] = [0] __a : int = [0] __a : str = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) __a : int = [60] __a : Union[str, Any] = [10] __a : Tuple = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = 3 __a : str = [1, 2, 3] __a : Optional[Any] = [3, 2, 1] __a : int = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 50 __a : Tuple = [60, 100, 120] __a : List[str] = [10, 20, 30] __a : Union[str, Any] = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 ) if __name__ == "__main__": unittest.main()
63
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): _lowerCAmelCase = ["pixel_values"] def __init__(self , _lowercase = True , _lowercase = None , _lowercase = PILImageResampling.BILINEAR , _lowercase = True , _lowercase = 1 / 255 , _lowercase = True , _lowercase = None , _lowercase = True , **_lowercase , ): '''simple docstring''' super().__init__(**_lowerCamelCase ) __a : Dict = size if size is not None else {"""shortest_edge""": 224} __a : Optional[int] = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) __a : Tuple = crop_size if crop_size is not None else {"""height""": 256, """width""": 256} __a : List[str] = get_size_dict(_lowerCamelCase , param_name="""crop_size""" ) __a : Any = do_resize __a : Any = size __a : Dict = resample __a : Union[str, Any] = do_rescale __a : int = rescale_factor __a : int = do_center_crop __a : int = crop_size __a : Union[str, Any] = do_flip_channel_order def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = PIL.Image.BILINEAR , _lowercase = None , **_lowercase , ): '''simple docstring''' __a : List[Any] = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}''' ) __a : Any = get_resize_output_image_size(_lowerCamelCase , size=size["""shortest_edge"""] , default_to_square=_lowerCamelCase ) return resize(_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = None , **_lowercase , ): '''simple docstring''' __a : Optional[Any] = get_size_dict(_lowerCamelCase ) 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()}''' ) return center_crop(_lowerCamelCase , size=(size["""height"""], size["""width"""]) , data_format=_lowerCamelCase , **_lowerCamelCase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = None , **_lowercase , ): '''simple docstring''' return rescale(_lowerCamelCase , scale=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' return flip_channel_order(_lowerCamelCase , data_format=_lowerCamelCase ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = ChannelDimension.FIRST , **_lowercase , ): '''simple docstring''' __a : Optional[Any] = do_resize if do_resize is not None else self.do_resize __a : List[str] = resample if resample is not None else self.resample __a : Dict = do_rescale if do_rescale is not None else self.do_rescale __a : int = rescale_factor if rescale_factor is not None else self.rescale_factor __a : str = do_center_crop if do_center_crop is not None else self.do_center_crop __a : int = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) __a : Any = size if size is not None else self.size __a : Tuple = get_size_dict(_lowerCamelCase , default_to_square=_lowerCamelCase ) __a : List[Any] = crop_size if crop_size is not None else self.crop_size __a : Optional[Any] = get_size_dict(_lowerCamelCase , param_name="""crop_size""" ) __a : Optional[Any] = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) # All transformations expect numpy arrays. __a : Tuple = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: __a : Union[str, Any] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_center_crop: __a : Any = [self.center_crop(image=_lowerCamelCase , size=_lowerCamelCase ) for image in images] if do_rescale: __a : Union[str, Any] = [self.rescale(image=_lowerCamelCase , scale=_lowerCamelCase ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: __a : Dict = [self.flip_channel_order(image=_lowerCamelCase ) for image in images] __a : Any = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] __a : List[Any] = {"""pixel_values""": images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase ) def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' __a : Tuple = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_lowerCamelCase ) != len(_lowerCamelCase ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(_lowerCamelCase ): __a : Dict = target_sizes.numpy() __a : Optional[int] = [] for idx in range(len(_lowerCamelCase ) ): __a : Optional[int] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=_lowerCamelCase ) __a : List[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_lowerCamelCase ) else: __a : int = logits.argmax(dim=1 ) __a : int = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
700
"""simple docstring""" from manim import * class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = Rectangle(height=0.5 , width=0.5 ) __a : Union[str, Any] = Rectangle(height=0.25 , width=0.25 ) __a : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a : Dict = [mem.copy() for i in range(6 )] __a : str = [mem.copy() for i in range(6 )] __a : Tuple = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Union[str, Any] = Text("""CPU""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(4 )] __a : Dict = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = Text("""GPU""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) gpu.move_to([-1, -1, 0] ) self.add(_lowercase ) __a : List[Any] = [mem.copy() for i in range(6 )] __a : Any = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Optional[Any] = Text("""Model""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) model.move_to([3, -1.0, 0] ) self.add(_lowercase ) __a : Tuple = [] __a : Tuple = [] __a : Optional[int] = [] for i, rect in enumerate(_lowercase ): rect.set_stroke(_lowercase ) __a : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_lowercase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowercase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_lowercase , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_lowercase , buff=0.0 ) self.add(_lowercase ) model_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase , *_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(6 )] __a : Union[str, Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Any = Text("""Loaded Checkpoint""" , font_size=24 ) __a : str = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) checkpoint.move_to([3, 0.5, 0] ) self.add(_lowercase ) __a : Dict = [] __a : int = [] for i, rect in enumerate(_lowercase ): __a : List[str] = fill.copy().set_fill(_lowercase , opacity=0.7 ) target.move_to(_lowercase ) ckpt_arr.append(_lowercase ) __a : Union[str, Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase ) __a : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a : List[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_lowercase , _lowercase ) __a : str = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_lowercase ) __a : Optional[int] = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) __a : List[Any] = [meta_mem.copy() for i in range(6 )] __a : Optional[int] = [meta_mem.copy() for i in range(6 )] __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Tuple = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Dict = Text("""Disk""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_lowercase , run_time=3 ) , Write(_lowercase , run_time=1 ) , Create(_lowercase , run_time=1 ) ) __a : Optional[Any] = [] for i, rect in enumerate(_lowercase ): __a : List[str] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_lowercase , run_time=1.5 ) ) self.play(*_lowercase ) self.play(FadeOut(_lowercase ) ) __a : List[str] = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_lowercase , run_time=3 ) ) self.play( FadeOut(_lowercase , _lowercase , *_lowercase , *_lowercase ) , ) self.wait()
63
0
"""simple docstring""" import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowercase__ = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ lowercase__ = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def __magic_name__ ( _lowerCamelCase : str ): __a : Tuple = numpy.dtype(numpy.uintaa ).newbyteorder(""">""" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=lowerCamelCase_ )[0] @deprecated(lowerCamelCase_ , """Please use tf.data to implement this functionality.""" ) def __magic_name__ ( _lowerCamelCase : Optional[Any] ): print("""Extracting""" , f.name ) with gzip.GzipFile(fileobj=lowerCamelCase_ ) as bytestream: __a : str = _readaa(lowerCamelCase_ ) if magic != 2_0_5_1: raise ValueError( """Invalid magic number %d in MNIST image file: %s""" % (magic, f.name) ) __a : List[str] = _readaa(lowerCamelCase_ ) __a : List[Any] = _readaa(lowerCamelCase_ ) __a : Dict = _readaa(lowerCamelCase_ ) __a : int = bytestream.read(rows * cols * num_images ) __a : int = numpy.frombuffer(lowerCamelCase_ , dtype=numpy.uinta ) __a : Optional[int] = data.reshape(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , 1 ) return data @deprecated(lowerCamelCase_ , """Please use tf.one_hot on tensors.""" ) def __magic_name__ ( _lowerCamelCase : Tuple , _lowerCamelCase : Union[str, Any] ): __a : List[Any] = labels_dense.shape[0] __a : int = numpy.arange(lowerCamelCase_ ) * num_classes __a : List[str] = numpy.zeros((num_labels, num_classes) ) __a : Optional[int] = 1 return labels_one_hot @deprecated(lowerCamelCase_ , """Please use tf.data to implement this functionality.""" ) def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : str=False , _lowerCamelCase : str=1_0 ): print("""Extracting""" , f.name ) with gzip.GzipFile(fileobj=lowerCamelCase_ ) as bytestream: __a : Tuple = _readaa(lowerCamelCase_ ) if magic != 2_0_4_9: raise ValueError( """Invalid magic number %d in MNIST label file: %s""" % (magic, f.name) ) __a : Any = _readaa(lowerCamelCase_ ) __a : Tuple = bytestream.read(lowerCamelCase_ ) __a : Any = numpy.frombuffer(lowerCamelCase_ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(lowerCamelCase_ , lowerCamelCase_ ) return labels class SCREAMING_SNAKE_CASE__ : @deprecated( __lowerCamelCase , """Please use alternatives such as official/mnist/_DataSet.py""" """ from tensorflow/models.""" , ) def __init__(self , _lowercase , _lowercase , _lowercase=False , _lowercase=False , _lowercase=dtypes.floataa , _lowercase=True , _lowercase=None , ): '''simple docstring''' __a : Union[str, Any] = random_seed.get_seed(__lowerCamelCase ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __a : int = dtypes.as_dtype(__lowerCamelCase ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("""Invalid image dtype %r, expected uint8 or float32""" % dtype ) if fake_data: __a : Any = 10000 __a : Optional[int] = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F'''images.shape: {images.shape} labels.shape: {labels.shape}''' __a : int = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __a : Any = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __a : Union[str, Any] = images.astype(numpy.floataa ) __a : Dict = numpy.multiply(__lowerCamelCase , 1.0 / 255.0 ) __a : Optional[int] = images __a : int = labels __a : Optional[Any] = 0 __a : Tuple = 0 @property def lowerCAmelCase__(self ): '''simple docstring''' return self._images @property def lowerCAmelCase__(self ): '''simple docstring''' return self._labels @property def lowerCAmelCase__(self ): '''simple docstring''' return self._num_examples @property def lowerCAmelCase__(self ): '''simple docstring''' return self._epochs_completed def lowerCAmelCase__(self , _lowercase , _lowercase=False , _lowercase=True ): '''simple docstring''' if fake_data: __a : str = [1] * 784 __a : Dict = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(__lowerCamelCase )], [fake_label for _ in range(__lowerCamelCase )], ) __a : Dict = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __a : Optional[int] = numpy.arange(self._num_examples ) numpy.random.shuffle(__lowerCamelCase ) __a : List[Any] = self.images[perma] __a : List[str] = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __a : Optional[Any] = self._num_examples - start __a : List[str] = self._images[start : self._num_examples] __a : Any = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __a : Tuple = numpy.arange(self._num_examples ) numpy.random.shuffle(__lowerCamelCase ) __a : int = self.images[perm] __a : str = self.labels[perm] # Start next epoch __a : Dict = 0 __a : Union[str, Any] = batch_size - rest_num_examples __a : Any = self._index_in_epoch __a : Optional[Any] = self._images[start:end] __a : List[Any] = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __a : str = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(lowerCamelCase_ , """Please write your own downloading logic.""" ) def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : int ): if not gfile.Exists(lowerCamelCase_ ): gfile.MakeDirs(lowerCamelCase_ ) __a : str = os.path.join(lowerCamelCase_ , lowerCamelCase_ ) if not gfile.Exists(lowerCamelCase_ ): urllib.request.urlretrieve(lowerCamelCase_ , lowerCamelCase_ ) # noqa: S310 with gfile.GFile(lowerCamelCase_ ) as f: __a : Any = f.size() print("""Successfully downloaded""" , lowerCamelCase_ , lowerCamelCase_ , """bytes.""" ) return filepath @deprecated( lowerCamelCase_ , """Please use alternatives such as:""" """ tensorflow_datasets.load(\'mnist\')""" ) def __magic_name__ ( _lowerCamelCase : Dict , _lowerCamelCase : Any=False , _lowerCamelCase : str=False , _lowerCamelCase : Optional[int]=dtypes.floataa , _lowerCamelCase : List[str]=True , _lowerCamelCase : Any=5_0_0_0 , _lowerCamelCase : Dict=None , _lowerCamelCase : List[Any]=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=lowerCamelCase_ , one_hot=lowerCamelCase_ , dtype=lowerCamelCase_ , seed=lowerCamelCase_ ) __a : List[str] = fake() __a : List[Any] = fake() __a : int = fake() return _Datasets(train=lowerCamelCase_ , validation=lowerCamelCase_ , test=lowerCamelCase_ ) if not source_url: # empty string check __a : List[Any] = DEFAULT_SOURCE_URL __a : Tuple = '''train-images-idx3-ubyte.gz''' __a : Optional[int] = '''train-labels-idx1-ubyte.gz''' __a : Optional[int] = '''t10k-images-idx3-ubyte.gz''' __a : List[Any] = '''t10k-labels-idx1-ubyte.gz''' __a : Optional[Any] = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + train_images_file ) with gfile.Open(lowerCamelCase_ , """rb""" ) as f: __a : Optional[int] = _extract_images(lowerCamelCase_ ) __a : Optional[int] = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + train_labels_file ) with gfile.Open(lowerCamelCase_ , """rb""" ) as f: __a : Dict = _extract_labels(lowerCamelCase_ , one_hot=lowerCamelCase_ ) __a : List[str] = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + test_images_file ) with gfile.Open(lowerCamelCase_ , """rb""" ) as f: __a : int = _extract_images(lowerCamelCase_ ) __a : Tuple = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + test_labels_file ) with gfile.Open(lowerCamelCase_ , """rb""" ) as f: __a : str = _extract_labels(lowerCamelCase_ , one_hot=lowerCamelCase_ ) if not 0 <= validation_size <= len(lowerCamelCase_ ): __a : Tuple = ( '''Validation size should be between 0 and ''' F'''{len(lowerCamelCase_ )}. Received: {validation_size}.''' ) raise ValueError(lowerCamelCase_ ) __a : Any = train_images[:validation_size] __a : str = train_labels[:validation_size] __a : Any = train_images[validation_size:] __a : Any = train_labels[validation_size:] __a : Optional[Any] = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed} __a : List[str] = _DataSet(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) __a : List[Any] = _DataSet(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) __a : List[Any] = _DataSet(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) return _Datasets(train=lowerCamelCase_ , validation=lowerCamelCase_ , test=lowerCamelCase_ )
701
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float(moles / volume ) * nfactor ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (volume) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (pressure) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((pressure * volume) / (0.08_21 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
from importlib import import_module from .logging import get_logger lowercase__ = get_logger(__name__) class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase=None ): '''simple docstring''' __a : Union[str, Any] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , _lowercase , getattr(_lowercase , _lowercase ) ) __a : Optional[Any] = module._original_module if isinstance(_lowercase , _PatchedModuleObj ) else module class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = [] def __init__(self , _lowercase , _lowercase , _lowercase , _lowercase=None ): '''simple docstring''' __a : List[str] = obj __a : List[Any] = target __a : Any = new __a : List[str] = target.split(""".""" )[0] __a : Any = {} __a : str = attrs or [] def __enter__(self ): '''simple docstring''' *__a , __a : int = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(_lowercase ) ): try: __a : Optional[Any] = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): __a : List[Any] = getattr(self.obj , _lowercase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(_lowercase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): __a : Tuple = obj_attr # patch at top level setattr(self.obj , _lowercase , _PatchedModuleObj(_lowercase , attrs=self.attrs ) ) __a : List[Any] = getattr(self.obj , _lowercase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(_lowercase , _lowercase , _PatchedModuleObj(getattr(_lowercase , _lowercase , _lowercase ) , attrs=self.attrs ) ) __a : Optional[int] = getattr(_lowercase , _lowercase ) # finally set the target attribute setattr(_lowercase , _lowercase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: __a : Dict = getattr(import_module(""".""".join(_lowercase ) ) , _lowercase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , _lowercase ) is attr_value: __a : Optional[int] = getattr(self.obj , _lowercase ) setattr(self.obj , _lowercase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" __a : Any = globals()["""__builtins__"""][target_attr] setattr(self.obj , _lowercase , self.new ) else: raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__(self , *_lowercase ): '''simple docstring''' for attr in list(self.original ): setattr(self.obj , _lowercase , self.original.pop(_lowercase ) ) def lowerCAmelCase__(self ): '''simple docstring''' self.__enter__() self._active_patches.append(self ) def lowerCAmelCase__(self ): '''simple docstring''' try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
702
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : list[int] ): if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) __a : Any = sum(_lowerCamelCase ) / len(_lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
"""simple docstring""" 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 lowercase__ = logging.getLogger() @unittest.skip("Temporarily disable the doc tests." ) @require_torch @require_tf @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = True , ): '''simple docstring''' __a : Dict = [file for file in os.listdir(lowercase_ ) if os.path.isfile(os.path.join(lowercase_ , lowercase_ ) )] if identifier is not None: __a : Union[str, Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(lowercase_ , lowercase_ ): for n_ in n_identifier: __a : Optional[Any] = [file for file in files if n_ not in file] else: __a : Optional[Any] = [file for file in files if n_identifier not in file] __a : str = ignore_files or [] ignore_files.append("""__init__.py""" ) __a : str = [file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , lowercase_ ) if only_modules: __a : Optional[Any] = file.split(""".""" )[0] try: __a : int = getattr(lowercase_ , lowercase_ ) __a : Dict = doctest.DocTestSuite(lowercase_ ) __a : Dict = unittest.TextTestRunner().run(lowercase_ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'''{module_identifier} is not a module.''' ) else: __a : int = doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = Path("""src/transformers""" ) __a : Dict = "modeling" __a : Tuple = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(lowercase_ , identifier=lowercase_ , ignore_files=lowercase_ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : str = Path("""src/transformers""" ) __a : Optional[Any] = "tokenization" self.analyze_directory(lowercase_ , identifier=lowercase_ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : str = Path("""src/transformers""" ) __a : Union[str, Any] = "configuration" self.analyze_directory(lowercase_ , identifier=lowercase_ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = Path("""src/transformers""" ) __a : Dict = ["configuration", "modeling", "tokenization"] self.analyze_directory(lowercase_ , n_identifier=lowercase_ ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = Path("""docs/source""" ) __a : Any = ["favicon.ico"] self.analyze_directory(lowercase_ , ignore_files=lowercase_ , only_modules=lowercase_ )
703
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math.sqrt(_lowerCamelCase ) __a : Any = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): __a : Any = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float ): # Creates a gaussian kernel of given dimension. __a : int = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowerCamelCase ): for j in range(0 , _lowerCamelCase ): __a : Any = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int , ): __a : Tuple = np.zeros(img.shape ) __a : Optional[int] = get_gauss_kernel(_lowerCamelCase , _lowerCamelCase ) __a , __a : int = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): __a : List[str] = get_slice(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Any = img_s - img_s[kernel_size // 2, kernel_size // 2] __a : Optional[Any] = vec_gaussian(_lowerCamelCase , _lowerCamelCase ) __a : Optional[Any] = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Any = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Tuple = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) __a : Optional[Any] = val return imga def __magic_name__ ( _lowerCamelCase : list ): __a : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" __a : Union[str, Any] = float(args[2] ) if args[2:] else 1.0 __a : Optional[int] = float(args[3] ) if args[3:] else 1.0 if args[4:]: __a : Any = int(args[4] ) __a : Any = kernel_size + abs(kernel_size % 2 - 1 ) else: __a : Optional[int] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": lowercase__ , lowercase__ , lowercase__ , lowercase__ = parse_args(sys.argv) lowercase__ = cva.imread(filename, 0) cva.imshow("input image", img) lowercase__ = img / 255 lowercase__ = out.astype("float32") lowercase__ = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) lowercase__ = out * 255 lowercase__ = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
63
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = "▁" lowercase__ = {"vocab_file": "sentencepiece.bpe.model"} lowercase__ = { "vocab_file": { "xlm-roberta-base": "https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large": "https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large-finetuned-conll02-dutch": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll02-spanish": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-english": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-german": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model" ), } } lowercase__ = { "xlm-roberta-base": 512, "xlm-roberta-large": 512, "xlm-roberta-large-finetuned-conll02-dutch": 512, "xlm-roberta-large-finetuned-conll02-spanish": 512, "xlm-roberta-large-finetuned-conll03-english": 512, "xlm-roberta-large-finetuned-conll03-german": 512, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = ['''input_ids''', '''attention_mask'''] def __init__(self , _lowercase , _lowercase="<s>" , _lowercase="</s>" , _lowercase="</s>" , _lowercase="<s>" , _lowercase="<unk>" , _lowercase="<pad>" , _lowercase="<mask>" , _lowercase = None , **_lowercase , ): '''simple docstring''' __a : Dict = AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __a : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __a : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) __a : int = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token __a : str = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __a : Dict = 1 __a : List[str] = len(self.sp_model ) + self.fairseq_offset __a : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__(self ): '''simple docstring''' __a : int = self.__dict__.copy() __a : Tuple = None __a : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__(self , _lowercase ): '''simple docstring''' __a : Optional[Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __a : List[str] = {} __a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a : List[str] = [self.cls_token_id] __a : Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' __a : List[str] = [self.sep_token_id] __a : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def lowerCAmelCase__(self ): '''simple docstring''' __a : str = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return self.sp_model.encode(A_ , out_type=A_ ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __a : Union[str, Any] = self.sp_model.PieceToId(A_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : str = """""".join(A_ ).replace(A_ , """ """ ).strip() return out_string def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' if not os.path.isdir(A_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return __a : List[Any] = os.path.join( A_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , """wb""" ) as fi: __a : int = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
704
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __magic_name__ ( ): __a : Dict = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 2_0, """a """ * 3_0, """b """ * 7], } __a : Optional[Any] = Dataset.from_dict(_lowerCamelCase ) return dataset class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = get_dataset() __a : List[Any] = make_duplicate_clusters(_lowercase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = get_dataset() __a , __a : Optional[Any] = deduplicate_dataset(_lowercase ) self.assertEqual(len(_lowercase ) , 2 ) print(_lowercase ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , _lowercase )
63
0
"""simple docstring""" import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class SCREAMING_SNAKE_CASE__ ( __lowercase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_lowercase , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(_lowercase , """neck_hidden_sizes""" ) ) self.parent.assertTrue(hasattr(_lowercase , """num_attention_heads""" ) ) class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase=13 , _lowercase=32 , _lowercase=2 , _lowercase=3 , _lowercase=640 , _lowercase=4 , _lowercase="silu" , _lowercase=3 , _lowercase=32 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=True , _lowercase=True , _lowercase=10 , _lowercase=None , ): '''simple docstring''' __a : int = parent __a : int = batch_size __a : Any = image_size __a : Optional[int] = patch_size __a : List[Any] = num_channels __a : Optional[Any] = last_hidden_size __a : Optional[int] = num_attention_heads __a : Any = hidden_act __a : Any = conv_kernel_size __a : str = output_stride __a : Dict = hidden_dropout_prob __a : Union[str, Any] = attention_probs_dropout_prob __a : List[str] = classifier_dropout_prob __a : str = use_labels __a : Any = is_training __a : Dict = num_labels __a : Union[str, Any] = initializer_range __a : Dict = scope def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Optional[int] = None __a : Union[str, Any] = None if self.use_labels: __a : int = ids_tensor([self.batch_size] , self.num_labels ) __a : List[str] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a : List[str] = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCAmelCase__(self ): '''simple docstring''' return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : List[Any] = MobileViTModel(config=_lowercase ) model.to(_lowercase ) model.eval() __a : List[Any] = model(_lowercase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = self.num_labels __a : int = MobileViTForImageClassification(_lowercase ) model.to(_lowercase ) model.eval() __a : Union[str, Any] = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = self.num_labels __a : Any = MobileViTForSemanticSegmentation(_lowercase ) model.to(_lowercase ) model.eval() __a : str = model(_lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __a : Tuple = model(_lowercase , labels=_lowercase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = self.prepare_config_and_inputs() __a : Tuple = config_and_inputs __a : Tuple = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( __lowercase , __lowercase , unittest.TestCase ): _lowerCAmelCase = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) _lowerCAmelCase = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : str = MobileViTModelTester(self ) __a : int = MobileViTConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViT does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""MobileViT does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""MobileViT does not output attentions""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : str = model_class(_lowercase ) __a : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Dict = [*signature.parameters.keys()] __a : Dict = ["pixel_values"] self.assertListEqual(arg_names[:1] , _lowercase ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : str = model_class(_lowercase ) model.to(_lowercase ) model.eval() with torch.no_grad(): __a : Any = model(**self._prepare_for_class(_lowercase , _lowercase ) ) __a : Tuple = outputs.hidden_states __a : Tuple = 5 self.assertEqual(len(_lowercase ) , _lowercase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __a : Any = 2 for i in range(len(_lowercase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : str = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Any = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[str] = MobileViTModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def __magic_name__ ( ): __a : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""" ) if is_vision_available() else None @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""" ).to(_lowercase ) __a : Dict = self.default_image_processor __a : Optional[Any] = prepare_img() __a : Union[str, Any] = image_processor(images=_lowercase , return_tensors="""pt""" ).to(_lowercase ) # forward pass with torch.no_grad(): __a : str = model(**_lowercase ) # verify the logits __a : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : List[str] = torch.tensor([-1.9364, -1.2327, -0.4653] ).to(_lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) __a : Optional[int] = model.to(_lowercase ) __a : str = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) __a : List[Any] = prepare_img() __a : Tuple = image_processor(images=_lowercase , return_tensors="""pt""" ).to(_lowercase ) # forward pass with torch.no_grad(): __a : int = model(**_lowercase ) __a : Any = outputs.logits # verify the logits __a : List[Any] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _lowercase ) __a : Optional[Any] = torch.tensor( [ [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]], [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]], ] , device=_lowercase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _lowercase , atol=1e-4 ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : int = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) __a : str = model.to(_lowercase ) __a : str = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) __a : List[str] = prepare_img() __a : List[Any] = image_processor(images=_lowercase , return_tensors="""pt""" ).to(_lowercase ) # forward pass with torch.no_grad(): __a : List[Any] = model(**_lowercase ) __a : List[str] = outputs.logits.detach().cpu() __a : Any = image_processor.post_process_semantic_segmentation(outputs=_lowercase , target_sizes=[(50, 60)] ) __a : Optional[Any] = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _lowercase ) __a : Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=_lowercase ) __a : Union[str, Any] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _lowercase )
705
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available lowercase__ = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline lowercase__ = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False) parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not") parser.add_argument("--steps", default=None, type=int, help="Num inference steps") lowercase__ = parser.parse_args() lowercase__ = "cpu" lowercase__ = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings" lowercase__ = "path-to-your-trained-model" lowercase__ = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: lowercase__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) lowercase__ = pipe.to(device) # to channels last lowercase__ = pipe.unet.to(memory_format=torch.channels_last) lowercase__ = pipe.vae.to(memory_format=torch.channels_last) lowercase__ = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: lowercase__ = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex lowercase__ = torch.randn(2, 4, 64, 64) lowercase__ = torch.rand(1) * 999 lowercase__ = torch.randn(2, 77, 768) lowercase__ = (sample, timestep, encoder_hidden_status) try: lowercase__ = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: lowercase__ = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) lowercase__ = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) lowercase__ = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: lowercase__ = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute lowercase__ = 666 lowercase__ = torch.Generator(device).manual_seed(seed) lowercase__ = {"generator": generator} if args.steps is not None: lowercase__ = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): lowercase__ = pipe(prompt, **generate_kwargs).images[0] # save image image.save("generated.png")
706
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "linear" _lowerCAmelCase = "cosine" _lowerCAmelCase = "cosine_with_restarts" _lowerCAmelCase = "polynomial" _lowerCAmelCase = "constant" _lowerCAmelCase = "constant_with_warmup" _lowerCAmelCase = "piecewise_constant" def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int = -1 ): return LambdaLR(_lowerCamelCase , lambda _lowerCamelCase : 1 , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1.0 , _lowerCamelCase ) ) return 1.0 return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : str , _lowerCamelCase : int = -1 ): __a : Optional[int] = {} __a : Any = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __a , __a : int = rule_str.split(""":""" ) __a : Optional[int] = int(_lowerCamelCase ) __a : str = float(_lowerCamelCase ) __a : int = value __a : Dict = float(rule_list[-1] ) def create_rules_function(_lowerCamelCase : str , _lowerCamelCase : Tuple ): def rule_func(_lowerCamelCase : int ) -> float: __a : Optional[Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(_lowerCamelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __a : Optional[int] = create_rules_function(_lowerCamelCase , _lowerCamelCase ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : str=-1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0.5 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Any ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(_lowerCamelCase ) * 2.0 * progress )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int = 1 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Optional[int] ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(_lowerCamelCase ) * progress) % 1.0) )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]=1E-7 , _lowerCamelCase : Optional[int]=1.0 , _lowerCamelCase : Optional[int]=-1 ): __a : Union[str, Any] = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __a : Tuple = lr_init - lr_end __a : int = num_training_steps - num_warmup_steps __a : Optional[int] = 1 - (current_step - num_warmup_steps) / decay_steps __a : List[str] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __magic_name__ ( _lowerCamelCase : Union[str, SchedulerType] , _lowerCamelCase : Optimizer , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 1 , _lowerCamelCase : float = 1.0 , _lowerCamelCase : int = -1 , ): __a : int = SchedulerType(_lowerCamelCase ) __a : Optional[int] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(_lowerCamelCase , last_epoch=_lowerCamelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(_lowerCamelCase , step_rules=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(_lowerCamelCase , num_warmup_steps=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , num_cycles=_lowerCamelCase , last_epoch=_lowerCamelCase , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , power=_lowerCamelCase , last_epoch=_lowerCamelCase , ) return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , last_epoch=_lowerCamelCase )
63
0
"""simple docstring""" from __future__ import annotations import os from collections.abc import Mapping lowercase__ = tuple[int, int] class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase ): '''simple docstring''' __a : set[int] = vertices __a : dict[EdgeT, int] = { (min(_lowercase ), max(_lowercase )): weight for edge, weight in edges.items() } def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) __a : Union[str, Any] = weight def lowerCAmelCase__(self ): '''simple docstring''' __a : Graph = Graph({min(self.vertices )} , {} ) __a : EdgeT __a : int __a : EdgeT __a : int while len(subgraph.vertices ) < len(self.vertices ): __a : Any = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: __a : int = edge __a : Optional[Any] = weight subgraph.add_edge(_lowercase , _lowercase ) return subgraph def __magic_name__ ( _lowerCamelCase : str = "p107_network.txt" ): __a : str = os.path.abspath(os.path.dirname(_lowerCamelCase ) ) __a : str = os.path.join(_lowerCamelCase , _lowerCamelCase ) __a : dict[EdgeT, int] = {} __a : list[str] __a : int __a : int with open(_lowerCamelCase ) as f: __a : Any = f.read().strip().split("""\n""" ) __a : Dict = [line.split(""",""" ) for line in data] for edgea in range(1 , len(_lowerCamelCase ) ): for edgea in range(_lowerCamelCase ): if adjaceny_matrix[edgea][edgea] != "-": __a : Tuple = int(adjaceny_matrix[edgea][edgea] ) __a : Graph = Graph(set(range(len(_lowerCamelCase ) ) ) , _lowerCamelCase ) __a : Graph = graph.prims_algorithm() __a : int = sum(graph.edges.values() ) __a : int = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(f'{solution() = }')
707
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=False ): __a : Dict = OmegaConf.load(_lowerCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_lowerCamelCase ) ) ) return config def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : int=None ): if conf_path is None: __a : str = """./model_checkpoints/vqgan_only.yaml""" __a : List[Any] = load_config(_lowerCamelCase , display=_lowerCamelCase ) __a : Dict = VQModel(**config.model.params ) if ckpt_path is None: __a : List[Any] = """./model_checkpoints/vqgan_only.pt""" __a : Tuple = torch.load(_lowerCamelCase , map_location=_lowerCamelCase ) if ".ckpt" in ckpt_path: __a : List[str] = sd["""state_dict"""] model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase ) model.to(_lowerCamelCase ) del sd return model def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : List[str] ): __a , __a , __a : Tuple = model.encode(_lowerCamelCase ) print(F'''VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}''' ) __a : Union[str, Any] = model.decode(_lowerCamelCase ) return xrec def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any]=False ): __a , __a : Optional[Any] = string.rsplit(""".""" , 1 ) if reload: __a : Optional[Any] = importlib.import_module(_lowerCamelCase ) importlib.reload(_lowerCamelCase ) return getattr(importlib.import_module(_lowerCamelCase , package=_lowerCamelCase ) , cls ) def __magic_name__ ( _lowerCamelCase : Any ): if "target" not in config: raise KeyError("""Expected key `target` to instantiate.""" ) return get_obj_from_str(config["""target"""] )(**config.get("""params""" , {} ) ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Dict , _lowerCamelCase : int=True , _lowerCamelCase : int=True ): __a : Union[str, Any] = instantiate_from_config(_lowerCamelCase ) if sd is not None: model.load_state_dict(_lowerCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : int ): # load the specified checkpoint if ckpt: __a : List[str] = torch.load(_lowerCamelCase , map_location="""cpu""" ) __a : Any = pl_sd["""global_step"""] print(F'''loaded model from global step {global_step}.''' ) else: __a : List[Any] = {"""state_dict""": None} __a : Any = None __a : Union[str, Any] = load_model_from_config(config.model , pl_sd["""state_dict"""] , gpu=_lowerCamelCase , eval_mode=_lowerCamelCase )["""model"""] return model, global_step
63
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"} class SCREAMING_SNAKE_CASE__ ( __A ): _lowerCAmelCase = """openai-gpt""" _lowerCAmelCase = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__(self , _lowercase=40478 , _lowercase=512 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=1e-5 , _lowercase=0.02 , _lowercase="cls_index" , _lowercase=True , _lowercase=None , _lowercase=True , _lowercase=0.1 , **_lowercase , ): '''simple docstring''' __a : str = vocab_size __a : str = n_positions __a : str = n_embd __a : Dict = n_layer __a : List[str] = n_head __a : Tuple = afn __a : Union[str, Any] = resid_pdrop __a : int = embd_pdrop __a : Any = attn_pdrop __a : str = layer_norm_epsilon __a : List[str] = initializer_range __a : List[Any] = summary_type __a : Tuple = summary_use_proj __a : List[str] = summary_activation __a : Optional[int] = summary_first_dropout __a : List[Any] = summary_proj_to_labels super().__init__(**UpperCamelCase__ )
708
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase__ = { "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "LlamaForCausalLM", "LlamaModel", "LlamaPreTrainedModel", "LlamaForSequenceClassification", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def __magic_name__ ( _lowerCamelCase : Dict=None ): __a : Tuple = argparse.ArgumentParser(add_help=_lowerCamelCase , allow_abbrev=_lowerCamelCase ) # The main config parser __a : Optional[int] = config_command_parser(_lowerCamelCase ) # The subparser to add commands to __a : Optional[int] = config_parser.add_subparsers(title="""subcommands""" , dest="""subcommand""" ) # Then add other parsers with the parent parser default_command_parser(_lowerCamelCase , parents=[parent_parser] ) update_command_parser(_lowerCamelCase , parents=[parent_parser] ) return config_parser def __magic_name__ ( ): __a : Any = get_config_parser() __a : Union[str, Any] = config_parser.parse_args() if not hasattr(_lowerCamelCase , """func""" ): config_parser.print_help() exit(1 ) # Run args.func(_lowerCamelCase ) if __name__ == "__main__": main()
709
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "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 SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "unispeech" def __init__(self , _lowercase=32 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=1e-5 , _lowercase="group" , _lowercase="gelu" , _lowercase=(512, 512, 512, 512, 512, 512, 512) , _lowercase=(5, 2, 2, 2, 2, 2, 2) , _lowercase=(10, 3, 3, 3, 3, 2, 2) , _lowercase=False , _lowercase=128 , _lowercase=16 , _lowercase=False , _lowercase=True , _lowercase=0.05 , _lowercase=10 , _lowercase=2 , _lowercase=0.0 , _lowercase=10 , _lowercase=0 , _lowercase=320 , _lowercase=2 , _lowercase=0.1 , _lowercase=100 , _lowercase=256 , _lowercase=256 , _lowercase=0.1 , _lowercase="mean" , _lowercase=False , _lowercase=False , _lowercase=256 , _lowercase=80 , _lowercase=0 , _lowercase=1 , _lowercase=2 , _lowercase=0.5 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase ) __a : Union[str, Any] = hidden_size __a : Any = feat_extract_norm __a : Union[str, Any] = feat_extract_activation __a : Tuple = list(_lowercase ) __a : Dict = list(_lowercase ) __a : List[Any] = list(_lowercase ) __a : List[Any] = conv_bias __a : Optional[Any] = num_conv_pos_embeddings __a : Union[str, Any] = num_conv_pos_embedding_groups __a : Dict = len(self.conv_dim ) __a : Dict = num_hidden_layers __a : Union[str, Any] = intermediate_size __a : List[str] = hidden_act __a : int = num_attention_heads __a : int = hidden_dropout __a : Any = attention_dropout __a : List[Any] = activation_dropout __a : List[Any] = feat_proj_dropout __a : Union[str, Any] = final_dropout __a : str = layerdrop __a : Dict = layer_norm_eps __a : Dict = initializer_range __a : Union[str, Any] = num_ctc_classes __a : List[Any] = vocab_size __a : Any = do_stable_layer_norm __a : List[str] = use_weighted_layer_sum __a : List[str] = 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 __a : Dict = apply_spec_augment __a : Union[str, Any] = mask_time_prob __a : List[str] = mask_time_length __a : Dict = mask_time_min_masks __a : List[Any] = mask_feature_prob __a : Tuple = mask_feature_length __a : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __a : List[Any] = num_codevectors_per_group __a : Union[str, Any] = num_codevector_groups __a : List[Any] = contrastive_logits_temperature __a : Any = feat_quantizer_dropout __a : Optional[int] = num_negatives __a : List[str] = codevector_dim __a : List[Any] = proj_codevector_dim __a : Tuple = diversity_loss_weight # ctc loss __a : Any = ctc_loss_reduction __a : List[str] = ctc_zero_infinity # pretraining loss __a : Tuple = replace_prob @property def lowerCAmelCase__(self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
63
0
"""simple docstring""" import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) lowercase__ = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase_ ): def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=None , _lowercase=None ): '''simple docstring''' __a : Tuple = self.layer[current_layer](UpperCamelCase__ , UpperCamelCase__ , head_mask[current_layer] ) __a : Any = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." , lowercase_ , ) class SCREAMING_SNAKE_CASE__ ( lowercase_ ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__(UpperCamelCase__ ) __a : List[str] = BertEncoderWithPabee(UpperCamelCase__ ) self.init_weights() __a : List[Any] = 0 __a : Dict = 0 __a : Optional[int] = 0 __a : Tuple = 0 def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : Union[str, Any] = threshold def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : Union[str, Any] = patience def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = 0 __a : List[Any] = 0 def lowerCAmelCase__(self ): '''simple docstring''' __a : str = self.inference_layers_num / self.inference_instances_num __a : Optional[int] = ( F'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =''' F''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***''' ) print(UpperCamelCase__ ) @add_start_docstrings_to_model_forward(UpperCamelCase__ ) def lowerCAmelCase__(self , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=False , ): '''simple docstring''' if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: __a : Dict = input_ids.size() elif inputs_embeds is not None: __a : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) __a : str = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __a : int = torch.ones(UpperCamelCase__ , device=UpperCamelCase__ ) if token_type_ids is None: __a : int = torch.zeros(UpperCamelCase__ , dtype=torch.long , device=UpperCamelCase__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __a : List[str] = self.get_extended_attention_mask(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: __a , __a , __a : str = encoder_hidden_states.size() __a : str = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: __a : str = torch.ones(UpperCamelCase__ , device=UpperCamelCase__ ) __a : str = self.invert_attention_mask(UpperCamelCase__ ) else: __a : Optional[Any] = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __a : int = self.get_head_mask(UpperCamelCase__ , self.config.num_hidden_layers ) __a : List[str] = self.embeddings( input_ids=UpperCamelCase__ , position_ids=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , inputs_embeds=UpperCamelCase__ ) __a : int = embedding_output if self.training: __a : int = [] for i in range(self.config.num_hidden_layers ): __a : Optional[Any] = self.encoder.adaptive_forward( UpperCamelCase__ , current_layer=UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ ) __a : Dict = self.pooler(UpperCamelCase__ ) __a : Dict = output_layers[i](output_dropout(UpperCamelCase__ ) ) res.append(UpperCamelCase__ ) elif self.patience == 0: # Use all layers for inference __a : Tuple = self.encoder( UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , ) __a : Dict = self.pooler(encoder_outputs[0] ) __a : int = [output_layers[self.config.num_hidden_layers - 1](UpperCamelCase__ )] else: __a : List[str] = 0 __a : Tuple = None __a : Union[str, Any] = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 __a : int = self.encoder.adaptive_forward( UpperCamelCase__ , current_layer=UpperCamelCase__ , attention_mask=UpperCamelCase__ , head_mask=UpperCamelCase__ ) __a : Dict = self.pooler(UpperCamelCase__ ) __a : int = output_layers[i](UpperCamelCase__ ) if regression: __a : str = logits.detach() if patient_result is not None: __a : int = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: __a : Tuple = 0 else: __a : Union[str, Any] = logits.detach().argmax(dim=1 ) if patient_result is not None: __a : int = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(UpperCamelCase__ ) ): patient_counter += 1 else: __a : Dict = 0 __a : List[str] = logits if patient_counter == self.patience: break __a : Optional[Any] = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " , lowercase_ , ) class SCREAMING_SNAKE_CASE__ ( lowercase_ ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__(UpperCamelCase__ ) __a : Union[str, Any] = config.num_labels __a : Optional[Any] = BertModelWithPabee(UpperCamelCase__ ) __a : Union[str, Any] = nn.Dropout(config.hidden_dropout_prob ) __a : Tuple = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(UpperCamelCase__ ) def lowerCAmelCase__(self , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , ): '''simple docstring''' __a : Union[str, Any] = self.bert( input_ids=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , position_ids=UpperCamelCase__ , head_mask=UpperCamelCase__ , inputs_embeds=UpperCamelCase__ , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) __a : Union[str, Any] = (logits[-1],) if labels is not None: __a : Dict = None __a : Any = 0 for ix, logits_item in enumerate(UpperCamelCase__ ): if self.num_labels == 1: # We are doing regression __a : List[str] = MSELoss() __a : Union[str, Any] = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: __a : List[Any] = CrossEntropyLoss() __a : Any = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: __a : Optional[int] = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 __a : str = (total_loss / total_weights,) + outputs return outputs
710
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase = 13 , _lowercase = 64 , _lowercase = 2 , _lowercase = 3 , _lowercase = 3 , _lowercase = True , _lowercase = True , _lowercase = 128 , _lowercase=[16, 32, 64, 128] , _lowercase = 7 , _lowercase = 4 , _lowercase = 37 , _lowercase = "gelu" , _lowercase = 0.1 , _lowercase = 0.1 , _lowercase = 10 , _lowercase = 0.02 , _lowercase = 2 , _lowercase = 1 , _lowercase = 128 , _lowercase = [2, 2, 2, 2] , _lowercase = 2 , _lowercase = 2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : int = image_size __a : Tuple = patch_size __a : str = num_channels __a : Union[str, Any] = is_training __a : List[Any] = use_labels __a : int = hidden_size __a : Optional[Any] = num_hidden_layers __a : List[Any] = num_attention_heads __a : Dict = intermediate_size __a : str = hidden_act __a : Dict = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Optional[int] = type_sequence_label_size __a : Dict = initializer_range __a : Dict = encoder_stride __a : int = num_attention_outputs __a : List[Any] = embed_dim __a : Optional[Any] = embed_dim + 1 __a : Optional[Any] = resolution __a : Optional[Any] = depths __a : Union[str, Any] = hidden_sizes __a : List[str] = dim __a : Any = mlp_expansion_ratio def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_labels: __a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowercase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = TFEfficientFormerModel(config=_lowercase ) __a : List[Any] = model(_lowercase , training=_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = self.type_sequence_label_size __a : Any = TFEfficientFormerForImageClassification(_lowercase ) __a : Union[str, Any] = model(_lowercase , labels=_lowercase , training=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a : Optional[Any] = 1 __a : int = TFEfficientFormerForImageClassification(_lowercase ) __a : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : str = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _lowerCAmelCase = ( { "feature-extraction": TFEfficientFormerModel, "image-classification": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = TFEfficientFormerModelTester(self ) __a : Any = ConfigTester( self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(_lowercase ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Union[str, Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : Tuple = model_class(_lowercase ) __a : int = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a : str = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_lowercase ) , _lowercase ) if hasattr(self.model_tester , """encoder_seq_length""" ): __a : Any = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: __a : int = seq_length * self.model_tester.chunk_length else: __a : Any = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __a : Optional[int] = outputs.decoder_hidden_states self.asseretIsInstance(_lowercase , (list, tuple) ) self.assertEqual(len(_lowercase ) , _lowercase ) __a : Any = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : List[Any] = getattr(self.model_tester , """decoder_seq_length""" , _lowercase ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : int = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' __a : Any = super()._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = TFEfficientFormerModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : int = True __a : Optional[int] = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """encoder_seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """key_length""" , _lowercase ) __a : int = getattr(self.model_tester , """chunk_length""" , _lowercase ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): __a : List[str] = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __a : List[Any] = True __a : Tuple = False __a : List[Any] = True __a : int = model_class(_lowercase ) __a : List[Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Dict = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a : Optional[Any] = True __a : List[str] = model_class(_lowercase ) __a : Dict = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : int = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __a : Dict = model_class(_lowercase ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __a : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=_lowercase ) for key, val in model.input_signature.items() if key in model.dummy_inputs } __a : Optional[Any] = model(_lowercase ) self.assertTrue(outputs_dict is not None ) def __magic_name__ ( ): __a : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : str = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) __a : Optional[Any] = self.default_image_processor __a : List[str] = prepare_img() __a : int = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : Optional[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : str = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : Dict = tf.constant([-0.0555, 0.4825, -0.0852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) __a : Any = self.default_image_processor __a : str = prepare_img() __a : str = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : List[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : int = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : List[str] = tf.constant([-0.1312, 0.4353, -1.0499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[str] ): while a != 0: __a , __a : Any = b % a, a return b def __magic_name__ ( _lowerCamelCase : List[str] , _lowerCamelCase : int ): if gcd(__lowerCAmelCase , __lowerCAmelCase ) != 1: __a : List[Any] = F'''mod inverse of {a!r} and {m!r} does not exist''' raise ValueError(__lowerCAmelCase ) __a , __a , __a : Any = 1, 0, a __a , __a , __a : Dict = 0, 1, m while va != 0: __a : Union[str, Any] = ua // va __a , __a , __a , __a , __a , __a : Optional[Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
711
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=0 ): '''simple docstring''' __a : Any = 1.0 if scale is None else scale __a : str = 0.0 if loc is None else loc super().__init__(_lowercase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=_lowercase )] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.variance.sqrt() class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' super().__init__(**_lowercase ) __a : str = args_dim __a : List[Any] = nn.ModuleList([nn.Linear(_lowercase , _lowercase ) for dim in args_dim.values()] ) __a : Dict = domain_map def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[Any] = [proj(_lowercase ) for proj in self.proj] return self.domain_map(*_lowercase ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__() __a : Optional[int] = function def lowerCAmelCase__(self , _lowercase , *_lowercase ): '''simple docstring''' return self.function(_lowercase , *_lowercase ) class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 42 _lowerCAmelCase = 42 _lowerCAmelCase = 42 def __init__(self , _lowercase = 1 ): '''simple docstring''' __a : Optional[int] = dim __a : str = {k: dim * self.args_dim[k] for k in self.args_dim} def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if self.dim == 1: return self.distribution_class(*_lowercase ) else: return Independent(self.distribution_class(*_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , ): '''simple docstring''' __a : Tuple = self._base_distribution(_lowercase ) if loc is None and scale is None: return distr else: return AffineTransformed(_lowercase , loc=_lowercase , scale=_lowercase , event_dim=self.event_dim ) @property def lowerCAmelCase__(self ): '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.event_shape ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 0.0 def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return ParameterProjection( in_features=_lowercase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def lowerCAmelCase__(self , *_lowercase ): '''simple docstring''' raise NotImplementedError() @staticmethod def lowerCAmelCase__(_lowercase ): '''simple docstring''' return (x + torch.sqrt(torch.square(_lowercase ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"df": 1, "loc": 1, "scale": 1} _lowerCAmelCase = StudentT @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) __a : Optional[Any] = 2.0 + cls.squareplus(_lowercase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"loc": 1, "scale": 1} _lowerCAmelCase = Normal @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : str = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"total_count": 1, "logits": 1} _lowerCAmelCase = NegativeBinomial @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = cls.squareplus(_lowercase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a , __a : Optional[Any] = distr_args if self.dim == 1: return self.distribution_class(total_count=_lowercase , logits=_lowercase ) else: return Independent(self.distribution_class(total_count=_lowercase , logits=_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None ): '''simple docstring''' __a , __a : List[Any] = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
63
0
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): _lowerCAmelCase = "align_text_model" def __init__(self , _lowercase=30522 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=512 , _lowercase=2 , _lowercase=0.02 , _lowercase=1e-12 , _lowercase=0 , _lowercase="absolute" , _lowercase=True , **_lowercase , ): '''simple docstring''' super().__init__(**_UpperCAmelCase ) __a : Any = vocab_size __a : Union[str, Any] = hidden_size __a : Optional[Any] = num_hidden_layers __a : str = num_attention_heads __a : Optional[Any] = hidden_act __a : Optional[int] = intermediate_size __a : Any = hidden_dropout_prob __a : Any = attention_probs_dropout_prob __a : Union[str, Any] = max_position_embeddings __a : Tuple = type_vocab_size __a : Dict = initializer_range __a : str = layer_norm_eps __a : List[Any] = position_embedding_type __a : Optional[Any] = use_cache __a : Any = pad_token_id @classmethod def lowerCAmelCase__(cls , _lowercase , **_lowercase ): '''simple docstring''' cls._set_token_in_kwargs(_UpperCAmelCase ) __a : Any = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the text config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": __a : Any = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): _lowerCAmelCase = "align_vision_model" def __init__(self , _lowercase = 3 , _lowercase = 600 , _lowercase = 2.0 , _lowercase = 3.1 , _lowercase = 8 , _lowercase = [3, 3, 5, 3, 5, 5, 3] , _lowercase = [32, 16, 24, 40, 80, 112, 192] , _lowercase = [16, 24, 40, 80, 112, 192, 320] , _lowercase = [] , _lowercase = [1, 2, 2, 2, 1, 2, 1] , _lowercase = [1, 2, 2, 3, 3, 4, 1] , _lowercase = [1, 6, 6, 6, 6, 6, 6] , _lowercase = 0.25 , _lowercase = "swish" , _lowercase = 2560 , _lowercase = "mean" , _lowercase = 0.02 , _lowercase = 0.001 , _lowercase = 0.99 , _lowercase = 0.2 , **_lowercase , ): '''simple docstring''' super().__init__(**_UpperCAmelCase ) __a : Dict = num_channels __a : Dict = image_size __a : List[Any] = width_coefficient __a : Optional[int] = depth_coefficient __a : Optional[int] = depth_divisor __a : Any = kernel_sizes __a : List[str] = in_channels __a : Optional[Any] = out_channels __a : Union[str, Any] = depthwise_padding __a : Dict = strides __a : Union[str, Any] = num_block_repeats __a : Optional[Any] = expand_ratios __a : str = squeeze_expansion_ratio __a : Dict = hidden_act __a : List[Any] = hidden_dim __a : Optional[int] = pooling_type __a : Tuple = initializer_range __a : Dict = batch_norm_eps __a : Dict = batch_norm_momentum __a : Dict = drop_connect_rate __a : int = sum(_UpperCAmelCase ) * 4 @classmethod def lowerCAmelCase__(cls , _lowercase , **_lowercase ): '''simple docstring''' cls._set_token_in_kwargs(_UpperCAmelCase ) __a : int = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": __a : Optional[int] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): _lowerCAmelCase = "align" _lowerCAmelCase = True def __init__(self , _lowercase=None , _lowercase=None , _lowercase=640 , _lowercase=1.0 , _lowercase=0.02 , **_lowercase , ): '''simple docstring''' super().__init__(**_UpperCAmelCase ) if text_config is None: __a : List[str] = {} logger.info("""text_config is None. Initializing the AlignTextConfig with default values.""" ) if vision_config is None: __a : Tuple = {} logger.info("""vision_config is None. Initializing the AlignVisionConfig with default values.""" ) __a : Union[str, Any] = AlignTextConfig(**_UpperCAmelCase ) __a : Any = AlignVisionConfig(**_UpperCAmelCase ) __a : int = projection_dim __a : Union[str, Any] = temperature_init_value __a : Dict = initializer_range @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_UpperCAmelCase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = copy.deepcopy(self.__dict__ ) __a : str = self.text_config.to_dict() __a : List[str] = self.vision_config.to_dict() __a : List[Any] = self.__class__.model_type return output
712
"""simple docstring""" import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = KandinskyVaaPriorPipeline _lowerCAmelCase = ["prompt"] _lowerCAmelCase = ["prompt", "negative_prompt"] _lowerCAmelCase = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] _lowerCAmelCase = False @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim * 4 @property def lowerCAmelCase__(self ): '''simple docstring''' return 100 @property def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_lowercase ) @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : Dict = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a : Tuple = PriorTransformer(**_lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a : int = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[str] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a : Optional[Any] = CLIPVisionModelWithProjection(_lowercase ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = CLIPImageProcessor( crop_size=224 , do_center_crop=_lowercase , do_normalize=_lowercase , do_resize=_lowercase , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.dummy_prior __a : int = self.dummy_image_encoder __a : Any = self.dummy_text_encoder __a : int = self.dummy_tokenizer __a : Optional[Any] = self.dummy_image_processor __a : List[Any] = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=_lowercase , clip_sample_range=10.0 , ) __a : List[Any] = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def lowerCAmelCase__(self , _lowercase , _lowercase=0 ): '''simple docstring''' if str(_lowercase ).startswith("""mps""" ): __a : Dict = torch.manual_seed(_lowercase ) else: __a : Union[str, Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a : Union[str, Any] = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = """cpu""" __a : Union[str, Any] = self.get_dummy_components() __a : Dict = self.pipeline_class(**_lowercase ) __a : Tuple = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = pipe(**self.get_dummy_inputs(_lowercase ) ) __a : str = output.image_embeds __a : Any = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] __a : List[Any] = image[0, -10:] __a : List[Any] = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a : Optional[Any] = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = torch_device == """cpu""" __a : Any = True __a : Any = False self._test_inference_batch_single_identical( test_max_difference=_lowercase , relax_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , ) @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = torch_device == """cpu""" __a : Union[str, Any] = False self._test_attention_slicing_forward_pass( test_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , )
63
0
"""simple docstring""" import re def __magic_name__ ( _lowerCamelCase : Optional[int] ): __a : Tuple = re.compile( r"""^(?:0|94|\+94|0{2}94)""" r"""7(0|1|2|4|5|6|7|8)""" r"""(-| |)""" r"""\d{7}$""" ) return bool(re.search(UpperCAmelCase__ , UpperCAmelCase__ ) ) if __name__ == "__main__": lowercase__ : str = "0094702343221" print(is_sri_lankan_phone_number(phone))
713
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = LEDTokenizer _lowerCAmelCase = LEDTokenizerFast _lowerCAmelCase = True def lowerCAmelCase__(self ): '''simple docstring''' super().setUp() __a : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __a : int = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) __a : Optional[int] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __a : List[Any] = {"""unk_token""": """<unk>"""} __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_lowercase ) ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] __a : List[str] = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer(_lowercase , max_length=len(_lowercase ) , padding=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __a : Dict = batch.input_ids.tolist()[0] self.assertListEqual(_lowercase , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Tuple = tokenizer(_lowercase , padding=_lowercase , return_tensors="""pt""" ) self.assertIn("""input_ids""" , _lowercase ) self.assertIn("""attention_mask""" , _lowercase ) self.assertNotIn("""labels""" , _lowercase ) self.assertNotIn("""decoder_attention_mask""" , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Dict = tokenizer(text_target=_lowercase , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer( ["""I am a small frog""" * 1024, """I am a small frog"""] , padding=_lowercase , truncation=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = ["""A long paragraph for summarization."""] __a : Dict = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : int = tokenizer(_lowercase , return_tensors="""pt""" ) __a : Dict = tokenizer(text_target=_lowercase , return_tensors="""pt""" ) __a : List[str] = inputs["""input_ids"""] __a : List[Any] = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[Any] = ["""Summary of the text.""", """Another summary."""] __a : List[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a : Union[str, Any] = tokenizer(_lowercase , padding=_lowercase ) __a : Tuple = [[0] * len(_lowercase ) for x in encoded_output["""input_ids"""]] __a : Union[str, Any] = tokenizer.pad(_lowercase ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __a : Dict = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = """A, <mask> AllenNLP sentence.""" __a : Dict = tokenizer_r.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) __a : Tuple = tokenizer_p.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) __a : Tuple = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) __a : Any = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
63
0
"""simple docstring""" from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
714
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=512, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def __magic_name__ ( _lowerCamelCase : Optional[Any] ): if string == "True": return True elif string == "False": return False else: raise ValueError(F'''could not parse string as bool {string}''' ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) lowercase__ = parser.parse_args() lowercase__ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int ): if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError("""Input must be an integer""" ) if input_num <= 0: raise ValueError("""Input must be positive""" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
715
"""simple docstring""" import torch from diffusers import DiffusionPipeline class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase ): '''simple docstring''' super().__init__() self.register_modules(unet=_lowercase , scheduler=_lowercase ) def __call__(self ): '''simple docstring''' __a : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __a : Optional[Any] = 1 __a : List[str] = self.unet(_lowercase , _lowercase ).sample __a : Union[str, Any] = self.scheduler.step(_lowercase , _lowercase , _lowercase ).prev_sample __a : Optional[int] = scheduler_output - scheduler_output + torch.ones_like(_lowercase ) return result
63
0
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__(self , _lowercase , _lowercase=7 , _lowercase=3 , _lowercase=30 , _lowercase=400 , _lowercase=True , _lowercase=None , _lowercase=True , _lowercase=[0.5, 0.5, 0.5] , _lowercase=[0.5, 0.5, 0.5] , _lowercase=True , _lowercase=1 / 255 , _lowercase=True , ): '''simple docstring''' __a : Optional[Any] = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333} __a : Union[str, Any] = parent __a : int = batch_size __a : Optional[int] = num_channels __a : Any = min_resolution __a : str = max_resolution __a : Union[str, Any] = do_resize __a : List[str] = size __a : Any = do_normalize __a : Tuple = image_mean __a : Tuple = image_std __a : List[str] = do_rescale __a : List[str] = rescale_factor __a : int = do_pad def lowerCAmelCase__(self ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowerCAmelCase__(self , _lowercase , _lowercase=False ): '''simple docstring''' if not batched: __a : Tuple = image_inputs[0] if isinstance(_lowercase , Image.Image ): __a , __a : Tuple = image.size else: __a , __a : Optional[Any] = image.shape[1], image.shape[2] if w < h: __a : Union[str, Any] = int(self.size["""shortest_edge"""] * h / w ) __a : Optional[int] = self.size["""shortest_edge"""] elif w > h: __a : str = self.size["""shortest_edge"""] __a : Union[str, Any] = int(self.size["""shortest_edge"""] * w / h ) else: __a : Optional[Any] = self.size["""shortest_edge"""] __a : Optional[int] = self.size["""shortest_edge"""] else: __a : List[Any] = [] for image in image_inputs: __a , __a : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a : Optional[int] = max(_lowercase , key=lambda _lowercase : item[0] )[0] __a : Union[str, Any] = max(_lowercase , key=lambda _lowercase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , unittest.TestCase ): _lowerCAmelCase = DetaImageProcessor if is_vision_available() else None def lowerCAmelCase__(self ): '''simple docstring''' __a : str = DetaImageProcessingTester(self ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowercase , """image_mean""" ) ) self.assertTrue(hasattr(_lowercase , """image_std""" ) ) self.assertTrue(hasattr(_lowercase , """do_normalize""" ) ) self.assertTrue(hasattr(_lowercase , """do_resize""" ) ) self.assertTrue(hasattr(_lowercase , """do_rescale""" ) ) self.assertTrue(hasattr(_lowercase , """do_pad""" ) ) self.assertTrue(hasattr(_lowercase , """size""" ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1333} ) self.assertEqual(image_processor.do_pad , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase ) for image in image_inputs: self.assertIsInstance(_lowercase , Image.Image ) # Test not batched input __a : Tuple = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __a , __a : List[str] = self.image_processor_tester.get_expected_values(_lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a : Dict = self.image_processor_tester.get_expected_values(_lowercase , batched=_lowercase ) __a : int = image_processing(_lowercase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase , numpify=_lowercase ) for image in image_inputs: self.assertIsInstance(_lowercase , np.ndarray ) # Test not batched input __a : Any = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __a , __a : List[Any] = self.image_processor_tester.get_expected_values(_lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a : Optional[int] = image_processing(_lowercase , return_tensors="""pt""" ).pixel_values __a , __a : Union[str, Any] = self.image_processor_tester.get_expected_values(_lowercase , batched=_lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase , torchify=_lowercase ) for image in image_inputs: self.assertIsInstance(_lowercase , torch.Tensor ) # Test not batched input __a : List[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __a , __a : Tuple = self.image_processor_tester.get_expected_values(_lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a : Union[str, Any] = image_processing(_lowercase , return_tensors="""pt""" ).pixel_values __a , __a : Union[str, Any] = self.image_processor_tester.get_expected_values(_lowercase , batched=_lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: __a : Union[str, Any] = json.loads(f.read() ) __a : Optional[int] = {"""image_id""": 39769, """annotations""": target} # encode them __a : Union[str, Any] = DetaImageProcessor() __a : str = image_processing(images=_lowercase , annotations=_lowercase , return_tensors="""pt""" ) # verify pixel values __a : str = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , _lowercase ) __a : Optional[int] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowercase , atol=1e-4 ) ) # verify area __a : int = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowercase ) ) # verify boxes __a : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowercase ) __a : Tuple = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowercase , atol=1e-3 ) ) # verify image_id __a : List[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowercase ) ) # verify is_crowd __a : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowercase ) ) # verify class_labels __a : int = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowercase ) ) # verify orig_size __a : Dict = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowercase ) ) # verify size __a : Dict = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowercase ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: __a : List[Any] = json.loads(f.read() ) __a : Dict = {"""file_name""": """000000039769.png""", """image_id""": 39769, """segments_info""": target} __a : Union[str, Any] = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them __a : Union[str, Any] = DetaImageProcessor(format="""coco_panoptic""" ) __a : List[Any] = image_processing(images=_lowercase , annotations=_lowercase , masks_path=_lowercase , return_tensors="""pt""" ) # verify pixel values __a : Optional[int] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , _lowercase ) __a : Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowercase , atol=1e-4 ) ) # verify area __a : Optional[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowercase ) ) # verify boxes __a : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowercase ) __a : str = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowercase , atol=1e-3 ) ) # verify image_id __a : Optional[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowercase ) ) # verify is_crowd __a : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowercase ) ) # verify class_labels __a : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowercase ) ) # verify masks __a : List[str] = 822873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , _lowercase ) # verify orig_size __a : List[str] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowercase ) ) # verify size __a : Optional[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowercase ) )
716
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json", # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "vit_msn" def __init__(self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1e-06 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=True , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase ) __a : int = hidden_size __a : str = num_hidden_layers __a : str = num_attention_heads __a : Optional[Any] = intermediate_size __a : Union[str, Any] = hidden_act __a : Tuple = hidden_dropout_prob __a : Any = attention_probs_dropout_prob __a : List[Any] = initializer_range __a : Any = layer_norm_eps __a : Dict = image_size __a : List[Any] = patch_size __a : Dict = num_channels __a : Optional[Any] = qkv_bias
63
0
"""simple docstring""" import math def __magic_name__ ( _lowerCamelCase : int = 1_0_0 ): __a : str = sum(i * i for i in range(1 , n + 1 ) ) __a : Tuple = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'{solution() = }')
717
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowercase__ = logging.get_logger(__name__) lowercase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRContextEncoderTokenizer class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRQuestionEncoderTokenizer lowercase__ = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) lowercase__ = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) lowercase__ = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ : def __call__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , **_lowercase , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) elif titles is None or texts is None: __a : str = titles if texts is None else texts return super().__call__( _lowercase , _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) __a : str = titles if not isinstance(_lowercase , _lowercase ) else [titles] __a : Optional[Any] = texts if not isinstance(_lowercase , _lowercase ) else [texts] __a : Tuple = len(_lowercase ) __a : Dict = questions if not isinstance(_lowercase , _lowercase ) else [questions] * n_passages assert len(_lowercase ) == len( _lowercase ), F'''There should be as many titles than texts but got {len(_lowercase )} titles and {len(_lowercase )} texts.''' __a : Optional[Any] = super().__call__(_lowercase , _lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : str = super().__call__(_lowercase , add_special_tokens=_lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : Union[str, Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowercase , _lowercase ) ] } if return_attention_mask is not False: __a : Optional[int] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __a : str = attention_mask return self.pad(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 16 , _lowercase = 64 , _lowercase = 4 , ): '''simple docstring''' __a : Union[str, Any] = reader_input["""input_ids"""] __a , __a , __a : Optional[int] = reader_output[:3] __a : int = len(_lowercase ) __a : Any = sorted(range(_lowercase ) , reverse=_lowercase , key=relevance_logits.__getitem__ ) __a : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __a : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __a : Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __a : int = sequence_ids.index(self.pad_token_id ) else: __a : Optional[Any] = len(_lowercase ) __a : List[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowercase , top_spans=_lowercase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowercase , start_index=_lowercase , end_index=_lowercase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowercase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' __a : Tuple = [] for start_index, start_score in enumerate(_lowercase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __a : str = sorted(_lowercase , key=lambda _lowercase : x[1] , reverse=_lowercase ) __a : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' __a : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowercase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = ["input_ids", "attention_mask"] _lowerCAmelCase = DPRReaderTokenizer
63
0
"""simple docstring""" from __future__ import annotations lowercase__ = [] def __magic_name__ ( _lowerCamelCase : list[list[int]] , _lowerCamelCase : int , _lowerCamelCase : int ): for i in range(len(snake_case_ ) ): if board[row][i] == 1: return False for i in range(len(snake_case_ ) ): if board[i][column] == 1: return False for i, j in zip(range(snake_case_ , -1 , -1 ) , range(snake_case_ , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(snake_case_ , -1 , -1 ) , range(snake_case_ , len(snake_case_ ) ) ): if board[i][j] == 1: return False return True def __magic_name__ ( _lowerCamelCase : list[list[int]] , _lowerCamelCase : int ): if row >= len(snake_case_ ): solution.append(snake_case_ ) printboard(snake_case_ ) print() return True for i in range(len(snake_case_ ) ): if is_safe(snake_case_ , snake_case_ , snake_case_ ): __a : Tuple = 1 solve(snake_case_ , row + 1 ) __a : str = 0 return False def __magic_name__ ( _lowerCamelCase : list[list[int]] ): for i in range(len(snake_case_ ) ): for j in range(len(snake_case_ ) ): if board[i][j] == 1: print("""Q""" , end=""" """ ) else: print(""".""" , end=""" """ ) print() # n=int(input("The no. of queens")) lowercase__ = 8 lowercase__ = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
718
"""simple docstring""" import os def __magic_name__ ( _lowerCamelCase : Dict ): __a : List[str] = len(grid[0] ) __a : int = len(_lowerCamelCase ) __a : Tuple = 0 __a : List[Any] = 0 __a : List[str] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_lowerCamelCase ): for j in range(n_rows - 3 ): __a : List[Any] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] __a : Tuple = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: __a : List[Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: __a : List[Any] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) __a : str = max( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if max_product > largest: __a : Optional[Any] = max_product return largest def __magic_name__ ( ): __a : Tuple = [] with open(os.path.dirname(_lowerCamelCase ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) __a : Tuple = [[int(_lowerCamelCase ) for i in grid[j]] for j in range(len(_lowerCamelCase ) )] return largest_product(_lowerCamelCase ) if __name__ == "__main__": print(solution())
63
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { """facebook/data2vec-vision-base-ft""": ( """https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE__ ( lowercase_ ): _lowerCAmelCase = '''data2vec-vision''' def __init__(self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1e-12 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=False , _lowercase=False , _lowercase=False , _lowercase=False , _lowercase=0.1 , _lowercase=0.1 , _lowercase=True , _lowercase=[3, 5, 7, 11] , _lowercase=[1, 2, 3, 6] , _lowercase=True , _lowercase=0.4 , _lowercase=256 , _lowercase=1 , _lowercase=False , _lowercase=255 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase ) __a : List[str] = hidden_size __a : int = num_hidden_layers __a : str = num_attention_heads __a : Tuple = intermediate_size __a : List[str] = hidden_act __a : Dict = hidden_dropout_prob __a : Optional[int] = attention_probs_dropout_prob __a : Any = initializer_range __a : Any = layer_norm_eps __a : Optional[int] = image_size __a : Tuple = patch_size __a : str = num_channels __a : Tuple = use_mask_token __a : Dict = use_absolute_position_embeddings __a : Dict = use_relative_position_bias __a : Optional[Any] = use_shared_relative_position_bias __a : Optional[int] = layer_scale_init_value __a : Any = drop_path_rate __a : Tuple = use_mean_pooling # decode head attributes (semantic segmentation) __a : Union[str, Any] = out_indices __a : List[str] = pool_scales # auxiliary head attributes (semantic segmentation) __a : Optional[Any] = use_auxiliary_head __a : int = auxiliary_loss_weight __a : List[str] = auxiliary_channels __a : Tuple = auxiliary_num_convs __a : List[Any] = auxiliary_concat_input __a : Optional[int] = semantic_loss_ignore_index class SCREAMING_SNAKE_CASE__ ( lowercase_ ): _lowerCAmelCase = version.parse("1.11" ) @property def lowerCAmelCase__(self ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 1e-4
719
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 42 _lowerCAmelCase = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
63
0
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : List[str]=1E-12 ): __a : Optional[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCamelCase__ , axis=1 ) , a_min=lowerCamelCase__ ) ).T __a : Dict = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCamelCase__ , axis=1 ) , a_min=lowerCamelCase__ ) ).T return jnp.matmul(lowerCamelCase__ , norm_emb_a.T ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): _lowerCAmelCase = 42 _lowerCAmelCase = jnp.floataa def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = FlaxCLIPVisionModule(self.config.vision_config ) __a : Tuple = nn.Dense(self.config.projection_dim , use_bias=_lowercase , dtype=self.dtype ) __a : Optional[Any] = self.param("""concept_embeds""" , jax.nn.initializers.ones , (17, self.config.projection_dim) ) __a : Any = self.param( """special_care_embeds""" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) __a : int = self.param("""concept_embeds_weights""" , jax.nn.initializers.ones , (17,) ) __a : int = self.param("""special_care_embeds_weights""" , jax.nn.initializers.ones , (3,) ) def __call__(self , _lowercase ): '''simple docstring''' __a : Dict = self.vision_model(_lowercase )[1] __a : Dict = self.visual_projection(_lowercase ) __a : Tuple = jax_cosine_distance(_lowercase , self.special_care_embeds ) __a : List[str] = jax_cosine_distance(_lowercase , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __a : str = 0.0 __a : int = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __a : int = jnp.round(_lowercase , 3 ) __a : Union[str, Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=_lowercase ) # Use a lower threshold if an image has any special care concept __a : Dict = is_special_care * 0.01 __a : List[Any] = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __a : List[str] = jnp.round(_lowercase , 3 ) __a : Dict = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = CLIPConfig _lowerCAmelCase = """clip_input""" _lowerCAmelCase = FlaxStableDiffusionSafetyCheckerModule def __init__(self , _lowercase , _lowercase = None , _lowercase = 0 , _lowercase = jnp.floataa , _lowercase = True , **_lowercase , ): '''simple docstring''' if input_shape is None: __a : str = (1, 224, 224, 3) __a : Optional[int] = self.module_class(config=_lowercase , dtype=_lowercase , **_lowercase ) super().__init__(_lowercase , _lowercase , input_shape=_lowercase , seed=_lowercase , dtype=_lowercase , _do_init=_do_init ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = None ): '''simple docstring''' __a : List[Any] = jax.random.normal(_lowercase , _lowercase ) __a , __a : Union[str, Any] = jax.random.split(_lowercase ) __a : str = {"""params""": params_rng, """dropout""": dropout_rng} __a : Any = self.module.init(_lowercase , _lowercase )["""params"""] return random_params def __call__(self , _lowercase , _lowercase = None , ): '''simple docstring''' __a : Dict = jnp.transpose(_lowercase , (0, 2, 3, 1) ) return self.module.apply( {"""params""": params or self.params} , jnp.array(_lowercase , dtype=jnp.floataa ) , rngs={} , )
720
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _lowerCAmelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCAmelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowerCAmelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowerCAmelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Optional[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __a : int = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : List[str] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __a : Optional[int] = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Tuple = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __a : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : Union[str, Any] = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __a : Optional[int] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __a : List[str] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = pipeline("""text-classification""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : Union[str, Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = pipeline("""text-classification""" , framework="""tf""" ) __a : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Tuple = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = TextClassificationPipeline(model=_lowercase , tokenizer=_lowercase ) return text_classifier, ["HuggingFace is in", "This is another test"] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __a : Union[str, Any] = """HuggingFace is in""" __a : List[str] = text_classifier(_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __a : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __a : Dict = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}, {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __a : Dict = text_classifier(_lowercase , top_k=_lowercase ) __a : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N, [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N] , ) __a : Dict = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __a : Any = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __a : Dict = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(_lowercase ): text_classifier(_lowercase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __a : Optional[int] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
63
0
"""simple docstring""" from __future__ import annotations def __magic_name__ ( _lowerCamelCase : list , _lowerCamelCase : int | None = None , _lowerCamelCase : int | None = None ): if start is None: __a : Union[str, Any] = 0 if end is None: __a : Dict = len(_lowerCamelCase ) - 1 if start >= end: return __a : int = (start + end) // 2 slowsort(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) slowsort(_lowerCamelCase , mid + 1 , _lowerCamelCase ) if sequence[end] < sequence[mid]: __a , __a : Optional[Any] = sequence[mid], sequence[end] slowsort(_lowerCamelCase , _lowerCamelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
721
"""simple docstring""" import unittest from knapsack import knapsack as k class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : str = 0 __a : Optional[Any] = [0] __a : int = [0] __a : str = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) __a : int = [60] __a : Union[str, Any] = [10] __a : Tuple = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = 3 __a : str = [1, 2, 3] __a : Optional[Any] = [3, 2, 1] __a : int = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 50 __a : Tuple = [60, 100, 120] __a : List[str] = [10, 20, 30] __a : Union[str, Any] = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 ) if __name__ == "__main__": unittest.main()
63
0
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES lowercase__ = logging.get_logger(__name__) lowercase__ = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) lowercase__ = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) lowercase__ = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) lowercase__ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) lowercase__ = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) lowercase__ = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) lowercase__ = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) lowercase__ = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) lowercase__ = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) lowercase__ = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) lowercase__ = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) lowercase__ = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) lowercase__ = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) lowercase__ = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) lowercase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) lowercase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) lowercase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) lowercase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) lowercase__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_MAPPING lowercase__ = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING lowercase__ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING lowercase__ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING lowercase__ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowercase__ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase__ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING lowercase__ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowercase__ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING lowercase__ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING lowercase__ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowercase__ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING lowercase__ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _lowerCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING lowercase__ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
700
"""simple docstring""" from manim import * class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = Rectangle(height=0.5 , width=0.5 ) __a : Union[str, Any] = Rectangle(height=0.25 , width=0.25 ) __a : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a : Dict = [mem.copy() for i in range(6 )] __a : str = [mem.copy() for i in range(6 )] __a : Tuple = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Union[str, Any] = Text("""CPU""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(4 )] __a : Dict = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = Text("""GPU""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) gpu.move_to([-1, -1, 0] ) self.add(_lowercase ) __a : List[Any] = [mem.copy() for i in range(6 )] __a : Any = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Optional[Any] = Text("""Model""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) model.move_to([3, -1.0, 0] ) self.add(_lowercase ) __a : Tuple = [] __a : Tuple = [] __a : Optional[int] = [] for i, rect in enumerate(_lowercase ): rect.set_stroke(_lowercase ) __a : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_lowercase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowercase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_lowercase , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_lowercase , buff=0.0 ) self.add(_lowercase ) model_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase , *_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(6 )] __a : Union[str, Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Any = Text("""Loaded Checkpoint""" , font_size=24 ) __a : str = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) checkpoint.move_to([3, 0.5, 0] ) self.add(_lowercase ) __a : Dict = [] __a : int = [] for i, rect in enumerate(_lowercase ): __a : List[str] = fill.copy().set_fill(_lowercase , opacity=0.7 ) target.move_to(_lowercase ) ckpt_arr.append(_lowercase ) __a : Union[str, Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase ) __a : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a : List[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_lowercase , _lowercase ) __a : str = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_lowercase ) __a : Optional[int] = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) __a : List[Any] = [meta_mem.copy() for i in range(6 )] __a : Optional[int] = [meta_mem.copy() for i in range(6 )] __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Tuple = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Dict = Text("""Disk""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_lowercase , run_time=3 ) , Write(_lowercase , run_time=1 ) , Create(_lowercase , run_time=1 ) ) __a : Optional[Any] = [] for i, rect in enumerate(_lowercase ): __a : List[str] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_lowercase , run_time=1.5 ) ) self.play(*_lowercase ) self.play(FadeOut(_lowercase ) ) __a : List[str] = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_lowercase , run_time=3 ) ) self.play( FadeOut(_lowercase , _lowercase , *_lowercase , *_lowercase ) , ) self.wait()
63
0
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = 0 def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(_lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __a : int = Path(_lowercase ) / """preprocessor_config.json""" __a : Dict = Path(_lowercase ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_lowercase , """w""" ) ) __a : Optional[int] = AutoImageProcessor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __a : Optional[int] = Path(_lowercase ) / """preprocessor_config.json""" __a : int = Path(_lowercase ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_lowercase , """w""" ) ) __a : Union[str, Any] = AutoImageProcessor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __a : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __a : Dict = Path(_lowercase ) / """preprocessor_config.json""" __a : Optional[Any] = Path(_lowercase ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_lowercase , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __a : Union[str, Any] = AutoImageProcessor.from_pretrained(_lowercase ).to_dict() config_dict.pop("""image_processor_type""" ) __a : Union[str, Any] = CLIPImageProcessor(**_lowercase ) # save in new folder model_config.save_pretrained(_lowercase ) config.save_pretrained(_lowercase ) __a : int = AutoImageProcessor.from_pretrained(_lowercase ) # make sure private variable is not incorrectly saved __a : Any = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(_lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __a : Dict = Path(_lowercase ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_lowercase , """w""" ) , ) __a : Optional[int] = AutoImageProcessor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' with self.assertRaisesRegex( _lowercase , """clip-base is not a local folder and is not a valid model identifier""" ): __a : Optional[Any] = AutoImageProcessor.from_pretrained("""clip-base""" ) def lowerCAmelCase__(self ): '''simple docstring''' with self.assertRaisesRegex( _lowercase , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): __a : Dict = AutoImageProcessor.from_pretrained(_lowercase , revision="""aaaaaa""" ) def lowerCAmelCase__(self ): '''simple docstring''' with self.assertRaisesRegex( _lowercase , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): __a : Optional[int] = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def lowerCAmelCase__(self ): '''simple docstring''' with self.assertRaises(_lowercase ): __a : List[Any] = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowercase ): __a : List[Any] = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_lowercase ) __a : Optional[Any] = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_lowercase ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowercase ) __a : Optional[Any] = AutoImageProcessor.from_pretrained(_lowercase , trust_remote_code=_lowercase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def lowerCAmelCase__(self ): '''simple docstring''' try: AutoConfig.register("""custom""" , _lowercase ) AutoImageProcessor.register(_lowercase , _lowercase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowercase ): AutoImageProcessor.register(_lowercase , _lowercase ) with tempfile.TemporaryDirectory() as tmpdirname: __a : Dict = Path(_lowercase ) / """preprocessor_config.json""" __a : List[str] = Path(_lowercase ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_lowercase , """w""" ) ) __a : Optional[Any] = CustomImageProcessor.from_pretrained(_lowercase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowercase ) __a : Optional[Any] = AutoImageProcessor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCAmelCase__(self ): '''simple docstring''' class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = True try: AutoConfig.register("""custom""" , _lowercase ) AutoImageProcessor.register(_lowercase , _lowercase ) # If remote code is not set, the default is to use local __a : List[Any] = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __a : Union[str, Any] = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_lowercase ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __a : Tuple = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_lowercase ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(_lowercase , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
701
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float(moles / volume ) * nfactor ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (volume) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (pressure) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((pressure * volume) / (0.08_21 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
from __future__ import annotations import math def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : bool , _lowerCamelCase : list[int] , _lowerCamelCase : float ): if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) if len(_lowerCamelCase ) == 0: raise ValueError("""Scores cannot be empty""" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , minimax(depth + 1 , node_index * 2 + 1 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , ) return min( minimax(depth + 1 , node_index * 2 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , minimax(depth + 1 , node_index * 2 + 1 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) , ) def __magic_name__ ( ): __a : Any = [9_0, 2_3, 6, 3_3, 2_1, 6_5, 1_2_3, 3_4_4_2_3] __a : Optional[Any] = math.log(len(_lowerCamelCase ) , 2 ) print("""Optimal value : """ , end="""""" ) print(minimax(0 , 0 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
702
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : list[int] ): if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) __a : Any = sum(_lowerCamelCase ) / len(_lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
"""simple docstring""" lowercase__ = 9.8_0665 def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float = g ): if fluid_density <= 0: raise ValueError("""Impossible fluid density""" ) if volume < 0: raise ValueError("""Impossible Object volume""" ) if gravity <= 0: raise ValueError("""Impossible Gravity""" ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
703
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math.sqrt(_lowerCamelCase ) __a : Any = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): __a : Any = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float ): # Creates a gaussian kernel of given dimension. __a : int = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowerCamelCase ): for j in range(0 , _lowerCamelCase ): __a : Any = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int , ): __a : Tuple = np.zeros(img.shape ) __a : Optional[int] = get_gauss_kernel(_lowerCamelCase , _lowerCamelCase ) __a , __a : int = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): __a : List[str] = get_slice(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Any = img_s - img_s[kernel_size // 2, kernel_size // 2] __a : Optional[Any] = vec_gaussian(_lowerCamelCase , _lowerCamelCase ) __a : Optional[Any] = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Any = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Tuple = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) __a : Optional[Any] = val return imga def __magic_name__ ( _lowerCamelCase : list ): __a : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" __a : Union[str, Any] = float(args[2] ) if args[2:] else 1.0 __a : Optional[int] = float(args[3] ) if args[3:] else 1.0 if args[4:]: __a : Any = int(args[4] ) __a : Any = kernel_size + abs(kernel_size % 2 - 1 ) else: __a : Optional[int] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": lowercase__ , lowercase__ , lowercase__ , lowercase__ = parse_args(sys.argv) lowercase__ = cva.imread(filename, 0) cva.imshow("input image", img) lowercase__ = img / 255 lowercase__ = out.astype("float32") lowercase__ = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) lowercase__ = out * 255 lowercase__ = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
63
0
"""simple docstring""" import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowercase__ = abspath(join(dirname(dirname(__file__)), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def __magic_name__ ( _lowerCamelCase : int ): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Tuple ): from diffusers.utils.testing_utils import pytest_terminal_summary_main __a : List[str] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(_lowerCamelCase , id=_lowerCamelCase )
704
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __magic_name__ ( ): __a : Dict = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 2_0, """a """ * 3_0, """b """ * 7], } __a : Optional[Any] = Dataset.from_dict(_lowerCamelCase ) return dataset class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = get_dataset() __a : List[Any] = make_duplicate_clusters(_lowercase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = get_dataset() __a , __a : Optional[Any] = deduplicate_dataset(_lowercase ) self.assertEqual(len(_lowercase ) , 2 ) print(_lowercase ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , _lowercase )
63
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE__ ( metaclass=__snake_case ): _lowerCAmelCase = ["keras_nlp"] def __init__(self , *_lowercase , **_lowercase ): '''simple docstring''' requires_backends(self , ["""keras_nlp"""] )
705
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available lowercase__ = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : list[str] ): __a : Tuple = """""" for word_or_phrase in separated: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise Exception("""join() accepts only strings to be joined""" ) joined += word_or_phrase + separator return joined.strip(_lowerCamelCase ) if __name__ == "__main__": from doctest import testmod testmod()
706
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "linear" _lowerCAmelCase = "cosine" _lowerCAmelCase = "cosine_with_restarts" _lowerCAmelCase = "polynomial" _lowerCAmelCase = "constant" _lowerCAmelCase = "constant_with_warmup" _lowerCAmelCase = "piecewise_constant" def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int = -1 ): return LambdaLR(_lowerCamelCase , lambda _lowerCamelCase : 1 , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1.0 , _lowerCamelCase ) ) return 1.0 return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : str , _lowerCamelCase : int = -1 ): __a : Optional[int] = {} __a : Any = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __a , __a : int = rule_str.split(""":""" ) __a : Optional[int] = int(_lowerCamelCase ) __a : str = float(_lowerCamelCase ) __a : int = value __a : Dict = float(rule_list[-1] ) def create_rules_function(_lowerCamelCase : str , _lowerCamelCase : Tuple ): def rule_func(_lowerCamelCase : int ) -> float: __a : Optional[Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(_lowerCamelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __a : Optional[int] = create_rules_function(_lowerCamelCase , _lowerCamelCase ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : str=-1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0.5 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Any ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(_lowerCamelCase ) * 2.0 * progress )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int = 1 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Optional[int] ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(_lowerCamelCase ) * progress) % 1.0) )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]=1E-7 , _lowerCamelCase : Optional[int]=1.0 , _lowerCamelCase : Optional[int]=-1 ): __a : Union[str, Any] = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __a : Tuple = lr_init - lr_end __a : int = num_training_steps - num_warmup_steps __a : Optional[int] = 1 - (current_step - num_warmup_steps) / decay_steps __a : List[str] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __magic_name__ ( _lowerCamelCase : Union[str, SchedulerType] , _lowerCamelCase : Optimizer , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 1 , _lowerCamelCase : float = 1.0 , _lowerCamelCase : int = -1 , ): __a : int = SchedulerType(_lowerCamelCase ) __a : Optional[int] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(_lowerCamelCase , last_epoch=_lowerCamelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(_lowerCamelCase , step_rules=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(_lowerCamelCase , num_warmup_steps=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , num_cycles=_lowerCamelCase , last_epoch=_lowerCamelCase , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , power=_lowerCamelCase , last_epoch=_lowerCamelCase , ) return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , last_epoch=_lowerCamelCase )
63
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase__ = logging.get_logger(__name__) lowercase__ = {"tokenizer_file": "tokenizer.json"} lowercase__ = { "tokenizer_file": { "bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json", "bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json", }, } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = ["input_ids", "attention_mask"] _lowerCAmelCase = None def __init__(self , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase="<unk>" , _lowercase="<s>" , _lowercase="</s>" , _lowercase="<pad>" , _lowercase=False , _lowercase=False , **_lowercase , ): '''simple docstring''' super().__init__( _lowercase , _lowercase , tokenizer_file=_lowercase , unk_token=_lowercase , bos_token=_lowercase , eos_token=_lowercase , pad_token=_lowercase , add_prefix_space=_lowercase , clean_up_tokenization_spaces=_lowercase , **_lowercase , ) __a : Optional[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , _lowercase ) != add_prefix_space: __a : str = getattr(_lowercase , pre_tok_state.pop("""type""" ) ) __a : Optional[int] = add_prefix_space __a : Any = pre_tok_class(**_lowercase ) __a : List[Any] = add_prefix_space def lowerCAmelCase__(self , *_lowercase , **_lowercase ): '''simple docstring''' __a : Dict = kwargs.get("""is_split_into_words""" , _lowercase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._batch_encode_plus(*_lowercase , **_lowercase ) def lowerCAmelCase__(self , *_lowercase , **_lowercase ): '''simple docstring''' __a : str = kwargs.get("""is_split_into_words""" , _lowercase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._encode_plus(*_lowercase , **_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' __a : int = self._tokenizer.model.save(_lowercase , name=_lowercase ) return tuple(_lowercase ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : Tuple = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_lowercase , add_special_tokens=_lowercase ) + [self.eos_token_id] ) if len(_lowercase ) > self.model_max_length: __a : int = input_ids[-self.model_max_length :] return input_ids
707
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=False ): __a : Dict = OmegaConf.load(_lowerCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_lowerCamelCase ) ) ) return config def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : int=None ): if conf_path is None: __a : str = """./model_checkpoints/vqgan_only.yaml""" __a : List[Any] = load_config(_lowerCamelCase , display=_lowerCamelCase ) __a : Dict = VQModel(**config.model.params ) if ckpt_path is None: __a : List[Any] = """./model_checkpoints/vqgan_only.pt""" __a : Tuple = torch.load(_lowerCamelCase , map_location=_lowerCamelCase ) if ".ckpt" in ckpt_path: __a : List[str] = sd["""state_dict"""] model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase ) model.to(_lowerCamelCase ) del sd return model def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : List[str] ): __a , __a , __a : Tuple = model.encode(_lowerCamelCase ) print(F'''VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}''' ) __a : Union[str, Any] = model.decode(_lowerCamelCase ) return xrec def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any]=False ): __a , __a : Optional[Any] = string.rsplit(""".""" , 1 ) if reload: __a : Optional[Any] = importlib.import_module(_lowerCamelCase ) importlib.reload(_lowerCamelCase ) return getattr(importlib.import_module(_lowerCamelCase , package=_lowerCamelCase ) , cls ) def __magic_name__ ( _lowerCamelCase : Any ): if "target" not in config: raise KeyError("""Expected key `target` to instantiate.""" ) return get_obj_from_str(config["""target"""] )(**config.get("""params""" , {} ) ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Dict , _lowerCamelCase : int=True , _lowerCamelCase : int=True ): __a : Union[str, Any] = instantiate_from_config(_lowerCamelCase ) if sd is not None: model.load_state_dict(_lowerCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : int ): # load the specified checkpoint if ckpt: __a : List[str] = torch.load(_lowerCamelCase , map_location="""cpu""" ) __a : Any = pl_sd["""global_step"""] print(F'''loaded model from global step {global_step}.''' ) else: __a : List[Any] = {"""state_dict""": None} __a : Any = None __a : Union[str, Any] = load_model_from_config(config.model , pl_sd["""state_dict"""] , gpu=_lowerCamelCase , eval_mode=_lowerCamelCase )["""model"""] return model, global_step
63
0
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = AudioLDMPipeline _lowerCAmelCase = TEXT_TO_AUDIO_PARAMS _lowerCAmelCase = TEXT_TO_AUDIO_BATCH_PARAMS _lowerCAmelCase = frozenset( [ "num_inference_steps", "num_waveforms_per_prompt", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=(32, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=_lowercase , ) __a : Optional[int] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_lowercase , set_alpha_to_one=_lowercase , ) torch.manual_seed(0 ) __a : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __a : str = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) __a : Any = ClapTextModelWithProjection(_lowercase ) __a : Optional[int] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) __a : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=16000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=_lowercase , ) __a : int = SpeechTaHifiGan(_lowercase ) __a : Union[str, Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def lowerCAmelCase__(self , _lowercase , _lowercase=0 ): '''simple docstring''' if str(_lowercase ).startswith("""mps""" ): __a : Any = torch.manual_seed(_lowercase ) else: __a : int = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a : List[Any] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator __a : int = self.get_dummy_components() __a : str = AudioLDMPipeline(**_lowercase ) __a : Union[str, Any] = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : Union[str, Any] = self.get_dummy_inputs(_lowercase ) __a : Optional[int] = audioldm_pipe(**_lowercase ) __a : Tuple = output.audios[0] assert audio.ndim == 1 assert len(_lowercase ) == 256 __a : Union[str, Any] = audio[:10] __a : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = self.get_dummy_components() __a : List[str] = AudioLDMPipeline(**_lowercase ) __a : Dict = audioldm_pipe.to(_lowercase ) __a : List[str] = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : List[str] = self.get_dummy_inputs(_lowercase ) __a : Any = 3 * [inputs["""prompt"""]] # forward __a : List[str] = audioldm_pipe(**_lowercase ) __a : Tuple = output.audios[0] __a : int = self.get_dummy_inputs(_lowercase ) __a : Optional[Any] = 3 * [inputs.pop("""prompt""" )] __a : str = audioldm_pipe.tokenizer( _lowercase , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=_lowercase , return_tensors="""pt""" , ) __a : Tuple = text_inputs["""input_ids"""].to(_lowercase ) __a : str = audioldm_pipe.text_encoder( _lowercase , ) __a : Optional[int] = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state __a : List[str] = F.normalize(_lowercase , dim=-1 ) __a : List[Any] = prompt_embeds # forward __a : Dict = audioldm_pipe(**_lowercase ) __a : Dict = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.get_dummy_components() __a : Any = AudioLDMPipeline(**_lowercase ) __a : Optional[Any] = audioldm_pipe.to(_lowercase ) __a : Dict = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : List[Any] = self.get_dummy_inputs(_lowercase ) __a : Optional[int] = 3 * ["""this is a negative prompt"""] __a : Union[str, Any] = negative_prompt __a : Dict = 3 * [inputs["""prompt"""]] # forward __a : Any = audioldm_pipe(**_lowercase ) __a : Union[str, Any] = output.audios[0] __a : Dict = self.get_dummy_inputs(_lowercase ) __a : Optional[Any] = 3 * [inputs.pop("""prompt""" )] __a : Union[str, Any] = [] for p in [prompt, negative_prompt]: __a : str = audioldm_pipe.tokenizer( _lowercase , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=_lowercase , return_tensors="""pt""" , ) __a : Optional[int] = text_inputs["""input_ids"""].to(_lowercase ) __a : Optional[int] = audioldm_pipe.text_encoder( _lowercase , ) __a : Optional[int] = text_embeds.text_embeds # additional L_2 normalization over each hidden-state __a : Tuple = F.normalize(_lowercase , dim=-1 ) embeds.append(_lowercase ) __a : int = embeds # forward __a : List[Any] = audioldm_pipe(**_lowercase ) __a : int = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator __a : int = self.get_dummy_components() __a : Tuple = PNDMScheduler(skip_prk_steps=_lowercase ) __a : Optional[int] = AudioLDMPipeline(**_lowercase ) __a : Optional[int] = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = self.get_dummy_inputs(_lowercase ) __a : Any = """egg cracking""" __a : Optional[Any] = audioldm_pipe(**_lowercase , negative_prompt=_lowercase ) __a : Tuple = output.audios[0] assert audio.ndim == 1 assert len(_lowercase ) == 256 __a : List[Any] = audio[:10] __a : Optional[Any] = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = """cpu""" # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Optional[int] = PNDMScheduler(skip_prk_steps=_lowercase ) __a : Any = AudioLDMPipeline(**_lowercase ) __a : Optional[int] = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) __a : Optional[int] = audioldm_pipe(_lowercase , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts __a : List[str] = 2 __a : int = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt __a : str = 2 __a : Tuple = audioldm_pipe(_lowercase , num_inference_steps=2 , num_waveforms_per_prompt=_lowercase ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts __a : List[Any] = 2 __a : List[Any] = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=_lowercase ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator __a : str = self.get_dummy_components() __a : Tuple = AudioLDMPipeline(**_lowercase ) __a : int = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : Union[str, Any] = audioldm_pipe.vocoder.config.sampling_rate __a : List[str] = self.get_dummy_inputs(_lowercase ) __a : str = audioldm_pipe(audio_length_in_s=0.016 , **_lowercase ) __a : List[Any] = output.audios[0] assert audio.ndim == 1 assert len(_lowercase ) / vocoder_sampling_rate == 0.016 __a : List[str] = audioldm_pipe(audio_length_in_s=0.032 , **_lowercase ) __a : Dict = output.audios[0] assert audio.ndim == 1 assert len(_lowercase ) / vocoder_sampling_rate == 0.032 def lowerCAmelCase__(self ): '''simple docstring''' __a : str = self.get_dummy_components() __a : Dict = AudioLDMPipeline(**_lowercase ) __a : List[str] = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = ["""hey"""] __a : List[Any] = audioldm_pipe(_lowercase , num_inference_steps=1 ) __a : List[Any] = output.audios.shape assert audio_shape == (1, 256) __a : Union[str, Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 __a : List[Any] = SpeechTaHifiGan(_lowercase ).to(_lowercase ) __a : Dict = audioldm_pipe(_lowercase , num_inference_steps=1 ) __a : int = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def lowerCAmelCase__(self ): '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' self._test_inference_batch_single_identical(test_mean_pixel_difference=_lowercase ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowerCAmelCase__(self ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_lowercase ) @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__(self , _lowercase , _lowercase="cpu" , _lowercase=torch.floataa , _lowercase=0 ): '''simple docstring''' __a : List[Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a : int = np.random.RandomState(_lowercase ).standard_normal((1, 8, 128, 16) ) __a : str = torch.from_numpy(_lowercase ).to(device=_lowercase , dtype=_lowercase ) __a : Dict = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) __a : Dict = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : str = self.get_inputs(_lowercase ) __a : Dict = 25 __a : Optional[int] = audioldm_pipe(**_lowercase ).audios[0] assert audio.ndim == 1 assert len(_lowercase ) == 81920 __a : List[Any] = audio[77230:77240] __a : Any = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) __a : Optional[Any] = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) __a : int = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) __a : Union[str, Any] = audioldm_pipe.to(_lowercase ) audioldm_pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = self.get_inputs(_lowercase ) __a : Union[str, Any] = audioldm_pipe(**_lowercase ).audios[0] assert audio.ndim == 1 assert len(_lowercase ) == 81920 __a : int = audio[27780:27790] __a : List[Any] = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) __a : Dict = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
708
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase__ = { "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "LlamaForCausalLM", "LlamaModel", "LlamaPreTrainedModel", "LlamaForSequenceClassification", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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 RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase=3 , _lowercase=32 , _lowercase=3 , _lowercase=10 , _lowercase=[10, 20, 30, 40] , _lowercase=[1, 1, 2, 1] , _lowercase=True , _lowercase=True , _lowercase="relu" , _lowercase=3 , _lowercase=None , ): '''simple docstring''' __a : Tuple = parent __a : str = batch_size __a : Any = image_size __a : int = num_channels __a : Union[str, Any] = embeddings_size __a : int = hidden_sizes __a : Any = depths __a : List[str] = is_training __a : int = use_labels __a : int = hidden_act __a : Optional[int] = num_labels __a : int = scope __a : List[Any] = len(_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Any = None if self.use_labels: __a : str = ids_tensor([self.batch_size] , self.num_labels ) __a : Tuple = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = RegNetModel(config=_lowercase ) model.to(_lowercase ) model.eval() __a : List[Any] = model(_lowercase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Tuple = self.num_labels __a : List[str] = RegNetForImageClassification(_lowercase ) model.to(_lowercase ) model.eval() __a : Tuple = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.prepare_config_and_inputs() __a : Any = config_and_inputs __a : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () _lowerCAmelCase = ( {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification} if is_torch_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : str = RegNetModelTester(self ) __a : Any = ConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase__(self ): '''simple docstring''' return @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = model_class(_lowercase ) __a : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : List[Any] = [*signature.parameters.keys()] __a : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(config=_lowercase ) for name, module in model.named_modules(): if isinstance(_lowercase , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : str = model_class(_lowercase ) model.to(_lowercase ) model.eval() with torch.no_grad(): __a : Optional[Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) ) __a : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a : Dict = self.model_tester.num_stages self.assertEqual(len(_lowercase ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __a : Any = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: __a : int = layer_type __a : List[str] = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Dict = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : str = RegNetModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def __magic_name__ ( ): __a : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_lowercase ) __a : Optional[Any] = self.default_image_processor __a : str = prepare_img() __a : List[str] = image_processor(images=_lowercase , return_tensors="""pt""" ).to(_lowercase ) # forward pass with torch.no_grad(): __a : Optional[Any] = model(**_lowercase ) # verify the logits __a : Any = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : Optional[Any] = torch.tensor([-0.4180, -1.5051, -3.4836] ).to(_lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
709
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "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 SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "unispeech" def __init__(self , _lowercase=32 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=1e-5 , _lowercase="group" , _lowercase="gelu" , _lowercase=(512, 512, 512, 512, 512, 512, 512) , _lowercase=(5, 2, 2, 2, 2, 2, 2) , _lowercase=(10, 3, 3, 3, 3, 2, 2) , _lowercase=False , _lowercase=128 , _lowercase=16 , _lowercase=False , _lowercase=True , _lowercase=0.05 , _lowercase=10 , _lowercase=2 , _lowercase=0.0 , _lowercase=10 , _lowercase=0 , _lowercase=320 , _lowercase=2 , _lowercase=0.1 , _lowercase=100 , _lowercase=256 , _lowercase=256 , _lowercase=0.1 , _lowercase="mean" , _lowercase=False , _lowercase=False , _lowercase=256 , _lowercase=80 , _lowercase=0 , _lowercase=1 , _lowercase=2 , _lowercase=0.5 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase ) __a : Union[str, Any] = hidden_size __a : Any = feat_extract_norm __a : Union[str, Any] = feat_extract_activation __a : Tuple = list(_lowercase ) __a : Dict = list(_lowercase ) __a : List[Any] = list(_lowercase ) __a : List[Any] = conv_bias __a : Optional[Any] = num_conv_pos_embeddings __a : Union[str, Any] = num_conv_pos_embedding_groups __a : Dict = len(self.conv_dim ) __a : Dict = num_hidden_layers __a : Union[str, Any] = intermediate_size __a : List[str] = hidden_act __a : int = num_attention_heads __a : int = hidden_dropout __a : Any = attention_dropout __a : List[Any] = activation_dropout __a : List[Any] = feat_proj_dropout __a : Union[str, Any] = final_dropout __a : str = layerdrop __a : Dict = layer_norm_eps __a : Dict = initializer_range __a : Union[str, Any] = num_ctc_classes __a : List[Any] = vocab_size __a : Any = do_stable_layer_norm __a : List[str] = use_weighted_layer_sum __a : List[str] = 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 __a : Dict = apply_spec_augment __a : Union[str, Any] = mask_time_prob __a : List[str] = mask_time_length __a : Dict = mask_time_min_masks __a : List[Any] = mask_feature_prob __a : Tuple = mask_feature_length __a : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __a : List[Any] = num_codevectors_per_group __a : Union[str, Any] = num_codevector_groups __a : List[Any] = contrastive_logits_temperature __a : Any = feat_quantizer_dropout __a : Optional[int] = num_negatives __a : List[str] = codevector_dim __a : List[Any] = proj_codevector_dim __a : Tuple = diversity_loss_weight # ctc loss __a : Any = ctc_loss_reduction __a : List[str] = ctc_zero_infinity # pretraining loss __a : Tuple = replace_prob @property def lowerCAmelCase__(self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
63
0
"""simple docstring""" import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , *_lowercase , _lowercase=None , _lowercase=None , **_lowercase ): '''simple docstring''' super().__init__(*_lowercase , **_lowercase ) __a : int = eval_examples __a : Optional[Any] = post_process_function def lowerCAmelCase__(self , _lowercase = None , _lowercase=None , _lowercase = None , _lowercase = "eval" , **_lowercase , ): '''simple docstring''' __a : Any = gen_kwargs.copy() __a : int = ( gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length""" ) is not None else self.args.generation_max_length ) __a : Optional[int] = ( gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams""" ) is not None else self.args.generation_num_beams ) __a : Tuple = gen_kwargs __a : Optional[int] = self.eval_dataset if eval_dataset is None else eval_dataset __a : Optional[Any] = self.get_eval_dataloader(_lowercase ) __a : Dict = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __a : Dict = self.compute_metrics __a : List[Any] = None __a : Dict = time.time() __a : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __a : Optional[Any] = eval_loop( _lowercase , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowercase , metric_key_prefix=_lowercase , ) finally: __a : List[str] = compute_metrics __a : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( _lowercase , _lowercase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default __a : Union[str, Any] = self.post_process_function(_lowercase , _lowercase , _lowercase ) __a : Tuple = self.compute_metrics(_lowercase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): __a : int = metrics.pop(_lowercase ) metrics.update(output.metrics ) else: __a : Any = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_lowercase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __a : str = self.callback_handler.on_evaluate(self.args , self.state , self.control , _lowercase ) return metrics def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=None , _lowercase = "test" , **_lowercase ): '''simple docstring''' __a : Dict = gen_kwargs.copy() __a : Tuple = self.get_test_dataloader(_lowercase ) # Temporarily disable metric computation, we will do it in the loop here. __a : Dict = self.compute_metrics __a : List[str] = None __a : Union[str, Any] = time.time() __a : List[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __a : str = eval_loop( _lowercase , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_lowercase , metric_key_prefix=_lowercase , ) finally: __a : Optional[int] = compute_metrics __a : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( _lowercase , _lowercase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output __a : str = self.post_process_function(_lowercase , _lowercase , _lowercase , """predict""" ) __a : Tuple = self.compute_metrics(_lowercase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): __a : Any = metrics.pop(_lowercase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_lowercase )
710
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase = 13 , _lowercase = 64 , _lowercase = 2 , _lowercase = 3 , _lowercase = 3 , _lowercase = True , _lowercase = True , _lowercase = 128 , _lowercase=[16, 32, 64, 128] , _lowercase = 7 , _lowercase = 4 , _lowercase = 37 , _lowercase = "gelu" , _lowercase = 0.1 , _lowercase = 0.1 , _lowercase = 10 , _lowercase = 0.02 , _lowercase = 2 , _lowercase = 1 , _lowercase = 128 , _lowercase = [2, 2, 2, 2] , _lowercase = 2 , _lowercase = 2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : int = image_size __a : Tuple = patch_size __a : str = num_channels __a : Union[str, Any] = is_training __a : List[Any] = use_labels __a : int = hidden_size __a : Optional[Any] = num_hidden_layers __a : List[Any] = num_attention_heads __a : Dict = intermediate_size __a : str = hidden_act __a : Dict = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Optional[int] = type_sequence_label_size __a : Dict = initializer_range __a : Dict = encoder_stride __a : int = num_attention_outputs __a : List[Any] = embed_dim __a : Optional[Any] = embed_dim + 1 __a : Optional[Any] = resolution __a : Optional[Any] = depths __a : Union[str, Any] = hidden_sizes __a : List[str] = dim __a : Any = mlp_expansion_ratio def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_labels: __a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowercase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = TFEfficientFormerModel(config=_lowercase ) __a : List[Any] = model(_lowercase , training=_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = self.type_sequence_label_size __a : Any = TFEfficientFormerForImageClassification(_lowercase ) __a : Union[str, Any] = model(_lowercase , labels=_lowercase , training=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a : Optional[Any] = 1 __a : int = TFEfficientFormerForImageClassification(_lowercase ) __a : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : str = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _lowerCAmelCase = ( { "feature-extraction": TFEfficientFormerModel, "image-classification": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = TFEfficientFormerModelTester(self ) __a : Any = ConfigTester( self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(_lowercase ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Union[str, Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : Tuple = model_class(_lowercase ) __a : int = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a : str = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_lowercase ) , _lowercase ) if hasattr(self.model_tester , """encoder_seq_length""" ): __a : Any = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: __a : int = seq_length * self.model_tester.chunk_length else: __a : Any = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __a : Optional[int] = outputs.decoder_hidden_states self.asseretIsInstance(_lowercase , (list, tuple) ) self.assertEqual(len(_lowercase ) , _lowercase ) __a : Any = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : List[Any] = getattr(self.model_tester , """decoder_seq_length""" , _lowercase ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : int = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' __a : Any = super()._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = TFEfficientFormerModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : int = True __a : Optional[int] = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """encoder_seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """key_length""" , _lowercase ) __a : int = getattr(self.model_tester , """chunk_length""" , _lowercase ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): __a : List[str] = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __a : List[Any] = True __a : Tuple = False __a : List[Any] = True __a : int = model_class(_lowercase ) __a : List[Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Dict = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a : Optional[Any] = True __a : List[str] = model_class(_lowercase ) __a : Dict = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : int = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __a : Dict = model_class(_lowercase ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __a : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=_lowercase ) for key, val in model.input_signature.items() if key in model.dummy_inputs } __a : Optional[Any] = model(_lowercase ) self.assertTrue(outputs_dict is not None ) def __magic_name__ ( ): __a : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : str = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) __a : Optional[Any] = self.default_image_processor __a : List[str] = prepare_img() __a : int = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : Optional[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : str = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : Dict = tf.constant([-0.0555, 0.4825, -0.0852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) __a : Any = self.default_image_processor __a : str = prepare_img() __a : str = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : List[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : int = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : List[str] = tf.constant([-0.1312, 0.4353, -1.0499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
63
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "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 SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "realm" def __init__(self , _lowercase=30522 , _lowercase=768 , _lowercase=128 , _lowercase=12 , _lowercase=12 , _lowercase=8 , _lowercase=3072 , _lowercase="gelu_new" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=512 , _lowercase=2 , _lowercase=0.02 , _lowercase=1e-12 , _lowercase=256 , _lowercase=10 , _lowercase=1e-3 , _lowercase=5 , _lowercase=320 , _lowercase=13353718 , _lowercase=5000 , _lowercase=1 , _lowercase=0 , _lowercase=2 , **_lowercase , ): '''simple docstring''' super().__init__(pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , **_lowercase ) # Common config __a : Any = vocab_size __a : Union[str, Any] = max_position_embeddings __a : int = hidden_size __a : Optional[int] = retriever_proj_size __a : int = num_hidden_layers __a : List[Any] = num_attention_heads __a : Union[str, Any] = num_candidates __a : int = intermediate_size __a : List[Any] = hidden_act __a : Dict = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : List[Any] = initializer_range __a : str = type_vocab_size __a : List[Any] = layer_norm_eps # Reader config __a : Any = span_hidden_size __a : List[Any] = max_span_width __a : Tuple = reader_layer_norm_eps __a : Dict = reader_beam_size __a : List[Any] = reader_seq_len # Retrieval config __a : str = num_block_records __a : int = searcher_beam_size
711
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=0 ): '''simple docstring''' __a : Any = 1.0 if scale is None else scale __a : str = 0.0 if loc is None else loc super().__init__(_lowercase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=_lowercase )] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.variance.sqrt() class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' super().__init__(**_lowercase ) __a : str = args_dim __a : List[Any] = nn.ModuleList([nn.Linear(_lowercase , _lowercase ) for dim in args_dim.values()] ) __a : Dict = domain_map def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[Any] = [proj(_lowercase ) for proj in self.proj] return self.domain_map(*_lowercase ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__() __a : Optional[int] = function def lowerCAmelCase__(self , _lowercase , *_lowercase ): '''simple docstring''' return self.function(_lowercase , *_lowercase ) class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 42 _lowerCAmelCase = 42 _lowerCAmelCase = 42 def __init__(self , _lowercase = 1 ): '''simple docstring''' __a : Optional[int] = dim __a : str = {k: dim * self.args_dim[k] for k in self.args_dim} def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if self.dim == 1: return self.distribution_class(*_lowercase ) else: return Independent(self.distribution_class(*_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , ): '''simple docstring''' __a : Tuple = self._base_distribution(_lowercase ) if loc is None and scale is None: return distr else: return AffineTransformed(_lowercase , loc=_lowercase , scale=_lowercase , event_dim=self.event_dim ) @property def lowerCAmelCase__(self ): '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.event_shape ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 0.0 def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return ParameterProjection( in_features=_lowercase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def lowerCAmelCase__(self , *_lowercase ): '''simple docstring''' raise NotImplementedError() @staticmethod def lowerCAmelCase__(_lowercase ): '''simple docstring''' return (x + torch.sqrt(torch.square(_lowercase ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"df": 1, "loc": 1, "scale": 1} _lowerCAmelCase = StudentT @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) __a : Optional[Any] = 2.0 + cls.squareplus(_lowercase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"loc": 1, "scale": 1} _lowerCAmelCase = Normal @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : str = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"total_count": 1, "logits": 1} _lowerCAmelCase = NegativeBinomial @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = cls.squareplus(_lowercase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a , __a : Optional[Any] = distr_args if self.dim == 1: return self.distribution_class(total_count=_lowercase , logits=_lowercase ) else: return Independent(self.distribution_class(total_count=_lowercase , logits=_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None ): '''simple docstring''' __a , __a : List[Any] = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
63
0
"""simple docstring""" import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 lowercase__ = 0b10_11_00_11_11_10_11_00_10_01_00_00_01_11_10_11_10_11_00_01_10_01_11_10 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 lowercase__ = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class SCREAMING_SNAKE_CASE__ : def __init__(self ): '''simple docstring''' __a : Any = WATERMARK_BITS __a : List[str] = WatermarkEncoder() self.encoder.set_watermark("""bits""" , self.watermark ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if images.shape[-1] < 256: return images __a : List[Any] = (255 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __a : List[str] = [self.encoder.encode(_lowercase , """dwtDct""" ) for image in images] __a : List[str] = torch.from_numpy(np.array(_lowercase ) ).permute(0 , 3 , 1 , 2 ) __a : Optional[Any] = torch.clamp(2 * (images / 255 - 0.5) , min=-1.0 , max=1.0 ) return images
712
"""simple docstring""" import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = KandinskyVaaPriorPipeline _lowerCAmelCase = ["prompt"] _lowerCAmelCase = ["prompt", "negative_prompt"] _lowerCAmelCase = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] _lowerCAmelCase = False @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim * 4 @property def lowerCAmelCase__(self ): '''simple docstring''' return 100 @property def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_lowercase ) @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : Dict = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a : Tuple = PriorTransformer(**_lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a : int = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[str] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a : Optional[Any] = CLIPVisionModelWithProjection(_lowercase ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = CLIPImageProcessor( crop_size=224 , do_center_crop=_lowercase , do_normalize=_lowercase , do_resize=_lowercase , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.dummy_prior __a : int = self.dummy_image_encoder __a : Any = self.dummy_text_encoder __a : int = self.dummy_tokenizer __a : Optional[Any] = self.dummy_image_processor __a : List[Any] = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=_lowercase , clip_sample_range=10.0 , ) __a : List[Any] = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def lowerCAmelCase__(self , _lowercase , _lowercase=0 ): '''simple docstring''' if str(_lowercase ).startswith("""mps""" ): __a : Dict = torch.manual_seed(_lowercase ) else: __a : Union[str, Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a : Union[str, Any] = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = """cpu""" __a : Union[str, Any] = self.get_dummy_components() __a : Dict = self.pipeline_class(**_lowercase ) __a : Tuple = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = pipe(**self.get_dummy_inputs(_lowercase ) ) __a : str = output.image_embeds __a : Any = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] __a : List[Any] = image[0, -10:] __a : List[Any] = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a : Optional[Any] = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = torch_device == """cpu""" __a : Any = True __a : Any = False self._test_inference_batch_single_identical( test_max_difference=_lowercase , relax_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , ) @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = torch_device == """cpu""" __a : Union[str, Any] = False self._test_attention_slicing_forward_pass( test_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , )
63
0
"""simple docstring""" from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def __magic_name__ ( ): __a : Tuple = ArgumentParser("""Transformers CLI tool""" , usage="""transformers-cli <command> [<args>]""" ) __a : Dict = parser.add_subparsers(help="""transformers-cli command helpers""" ) # Register commands ConvertCommand.register_subcommand(_lowerCamelCase ) DownloadCommand.register_subcommand(_lowerCamelCase ) EnvironmentCommand.register_subcommand(_lowerCamelCase ) RunCommand.register_subcommand(_lowerCamelCase ) ServeCommand.register_subcommand(_lowerCamelCase ) UserCommands.register_subcommand(_lowerCamelCase ) AddNewModelCommand.register_subcommand(_lowerCamelCase ) AddNewModelLikeCommand.register_subcommand(_lowerCamelCase ) LfsCommands.register_subcommand(_lowerCamelCase ) PTtoTFCommand.register_subcommand(_lowerCamelCase ) # Let's go __a : Union[str, Any] = parser.parse_args() if not hasattr(_lowerCamelCase , """func""" ): parser.print_help() exit(1 ) # Run __a : Optional[Any] = args.func(_lowerCamelCase ) service.run() if __name__ == "__main__": main()
713
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = LEDTokenizer _lowerCAmelCase = LEDTokenizerFast _lowerCAmelCase = True def lowerCAmelCase__(self ): '''simple docstring''' super().setUp() __a : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __a : int = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) __a : Optional[int] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __a : List[Any] = {"""unk_token""": """<unk>"""} __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_lowercase ) ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] __a : List[str] = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer(_lowercase , max_length=len(_lowercase ) , padding=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __a : Dict = batch.input_ids.tolist()[0] self.assertListEqual(_lowercase , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Tuple = tokenizer(_lowercase , padding=_lowercase , return_tensors="""pt""" ) self.assertIn("""input_ids""" , _lowercase ) self.assertIn("""attention_mask""" , _lowercase ) self.assertNotIn("""labels""" , _lowercase ) self.assertNotIn("""decoder_attention_mask""" , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Dict = tokenizer(text_target=_lowercase , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer( ["""I am a small frog""" * 1024, """I am a small frog"""] , padding=_lowercase , truncation=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = ["""A long paragraph for summarization."""] __a : Dict = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : int = tokenizer(_lowercase , return_tensors="""pt""" ) __a : Dict = tokenizer(text_target=_lowercase , return_tensors="""pt""" ) __a : List[str] = inputs["""input_ids"""] __a : List[Any] = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[Any] = ["""Summary of the text.""", """Another summary."""] __a : List[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a : Union[str, Any] = tokenizer(_lowercase , padding=_lowercase ) __a : Tuple = [[0] * len(_lowercase ) for x in encoded_output["""input_ids"""]] __a : Union[str, Any] = tokenizer.pad(_lowercase ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __a : Dict = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = """A, <mask> AllenNLP sentence.""" __a : Dict = tokenizer_r.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) __a : Tuple = tokenizer_p.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) __a : Tuple = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) __a : Any = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
63
0
"""simple docstring""" import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase = "cpu" , _lowercase = "openai/clip-vit-large-patch14" ): '''simple docstring''' __a : Any = device __a : Tuple = CLIPTokenizerFast.from_pretrained(_lowercase ) __a : List[str] = [0.4814_5466, 0.457_8275, 0.4082_1073] __a : Optional[Any] = [0.2686_2954, 0.2613_0258, 0.2757_7711] __a : Optional[int] = torchvision.transforms.Normalize(self.image_mean , self.image_std ) __a : Tuple = torchvision.transforms.Resize(224 ) __a : str = torchvision.transforms.CenterCrop(224 ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : int = self.resize(_lowercase ) __a : List[str] = self.center_crop(_lowercase ) __a : Union[str, Any] = self.normalize(_lowercase ) return images def __call__(self , _lowercase=None , _lowercase=None , **_lowercase ): '''simple docstring''' __a : Any = self.tokenizer(text=_lowercase , **_lowercase ) __a : Union[str, Any] = self.preprocess_img(_lowercase ) __a : Any = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase=10 , _lowercase=0.01 , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=False , _lowercase=True , _lowercase="image" , _lowercase=True , _lowercase=False , _lowercase=False , _lowercase=False , ): '''simple docstring''' super().__init__() __a : Any = None __a : Tuple = device if device else get_device() if vqgan: __a : Optional[Any] = vqgan else: __a : List[Any] = load_vqgan(self.device , conf_path=_lowercase , ckpt_path=_lowercase ) self.vqgan.eval() if clip: __a : str = clip else: __a : Dict = CLIPModel.from_pretrained("""openai/clip-vit-base-patch32""" ) self.clip.to(self.device ) __a : Any = ProcessorGradientFlow(device=self.device ) __a : Any = iterations __a : Optional[Any] = lr __a : Optional[Any] = log __a : Dict = make_grid __a : Dict = return_val __a : Tuple = quantize __a : Optional[Any] = self.vqgan.decoder.z_shape def lowerCAmelCase__(self , _lowercase=None , _lowercase=None , _lowercase=5 , _lowercase=True ): '''simple docstring''' __a : str = [] if output_path is None: __a : Optional[int] = """./animation.gif""" if input_path is None: __a : List[str] = self.save_path __a : Tuple = sorted(glob(input_path + """/*""" ) ) if not len(_lowercase ): raise ValueError( """No images found in save path, aborting (did you pass save_intermediate=True to the generate""" """ function?)""" ) if len(_lowercase ) == 1: print("""Only one image found in save path, (did you pass save_intermediate=True to the generate function?)""" ) __a : Union[str, Any] = total_duration / len(_lowercase ) __a : Optional[Any] = [frame_duration] * len(_lowercase ) if extend_frames: __a : Optional[int] = 1.5 __a : str = 3 for file_name in paths: if file_name.endswith(""".png""" ): images.append(imageio.imread(_lowercase ) ) imageio.mimsave(_lowercase , _lowercase , duration=_lowercase ) print(F'''gif saved to {output_path}''' ) def lowerCAmelCase__(self , _lowercase=None , _lowercase=None ): '''simple docstring''' if not (path or img): raise ValueError("""Input either path or tensor""" ) if img is not None: raise NotImplementedError __a : Any = preprocess(Image.open(_lowercase ) , target_image_size=256 ).to(self.device ) __a : str = preprocess_vqgan(_lowercase ) __a : List[str] = self.vqgan.encode(_lowercase ) return z def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[str] = self.latent.detach().requires_grad_() __a : Optional[Any] = base_latent + transform_vector if self.quantize: __a : str = self.vqgan.quantize(_lowercase ) else: __a : str = trans_latent return self.vqgan.decode(_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=None ): '''simple docstring''' __a : Tuple = self.clip_preprocessor(text=_lowercase , images=_lowercase , return_tensors="""pt""" , padding=_lowercase ) __a : Any = self.clip(**_lowercase ) __a : List[str] = clip_outputs.logits_per_image if weights is not None: __a : Optional[int] = similarity_logits * weights return similarity_logits.sum() def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Any = self._get_clip_similarity(pos_prompts["""prompts"""] , _lowercase , weights=(1 / pos_prompts["""weights"""]) ) if neg_prompts: __a : Tuple = self._get_clip_similarity(neg_prompts["""prompts"""] , _lowercase , weights=neg_prompts["""weights"""] ) else: __a : Any = torch.tensor([1] , device=self.device ) __a : Dict = -torch.log(_lowercase ) + torch.log(_lowercase ) return loss def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[int] = torch.randn_like(self.latent , requires_grad=_lowercase , device=self.device ) __a : List[Any] = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() __a : int = self._add_vector(_lowercase ) __a : Any = loop_post_process(_lowercase ) __a : Dict = self._get_CLIP_loss(_lowercase , _lowercase , _lowercase ) print("""CLIP loss""" , _lowercase ) if self.log: wandb.log({"""CLIP Loss""": clip_loss} ) clip_loss.backward(retain_graph=_lowercase ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' wandb.init(reinit=_lowercase , project="""face-editor""" ) wandb.config.update({"""Positive Prompts""": positive_prompts} ) wandb.config.update({"""Negative Prompts""": negative_prompts} ) wandb.config.update({"""lr""": self.lr, """iterations""": self.iterations} ) if image_path: __a : Optional[int] = Image.open(_lowercase ) __a : Union[str, Any] = image.resize((256, 256) ) wandb.log("""Original Image""" , wandb.Image(_lowercase ) ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if not prompts: return [] __a : Optional[Any] = [] __a : Optional[Any] = [] if isinstance(_lowercase , _lowercase ): __a : Dict = [prompt.strip() for prompt in prompts.split("""|""" )] for prompt in prompts: if isinstance(_lowercase , (tuple, list) ): __a : str = prompt[0] __a : Optional[Any] = float(prompt[1] ) elif ":" in prompt: __a : Optional[int] = prompt.split(""":""" ) __a : Any = float(_lowercase ) else: __a : Dict = prompt __a : List[str] = 1.0 processed_prompts.append(_lowercase ) weights.append(_lowercase ) return { "prompts": processed_prompts, "weights": torch.tensor(_lowercase , device=self.device ), } def lowerCAmelCase__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=True , _lowercase=False , _lowercase=True , _lowercase=True , _lowercase=None , ): '''simple docstring''' if image_path: __a : int = self._get_latent(_lowercase ) else: __a : Optional[Any] = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(_lowercase , _lowercase , _lowercase ) assert pos_prompts, "You must provide at least one positive prompt." __a : Union[str, Any] = self.process_prompts(_lowercase ) __a : Optional[Any] = self.process_prompts(_lowercase ) if save_final and save_path is None: __a : Dict = os.path.join("""./outputs/""" , """_""".join(pos_prompts["""prompts"""] ) ) if not os.path.exists(_lowercase ): os.makedirs(_lowercase ) else: __a : Union[str, Any] = save_path + """_""" + get_timestamp() os.makedirs(_lowercase ) __a : Tuple = save_path __a : str = self.vqgan.decode(self.latent )[0] if show_intermediate: print("""Original Image""" ) show_pil(custom_to_pil(_lowercase ) ) __a : Optional[int] = loop_post_process(_lowercase ) for iter, transformed_img in enumerate(self._optimize_CLIP(_lowercase , _lowercase , _lowercase ) ): if show_intermediate: show_pil(_lowercase ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , F'''iter_{iter:03d}.png''' ) ) if self.log: wandb.log({"""Image""": wandb.Image(_lowercase )} ) if show_final: show_pil(_lowercase ) if save_final: transformed_img.save(os.path.join(self.save_path , F'''iter_{iter:03d}_final.png''' ) )
714
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=512, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def __magic_name__ ( _lowerCamelCase : Optional[Any] ): if string == "True": return True elif string == "False": return False else: raise ValueError(F'''could not parse string as bool {string}''' ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) lowercase__ = parser.parse_args() lowercase__ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : List[str] ): __a : List[str] = 0 __a : Tuple = 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 __a : 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 __a : List[Any] = sorted_collection[point] if current_item == item: return point else: if point < left: __a : List[Any] = left __a : Any = point elif point > right: __a : List[Any] = right __a : Tuple = point else: if item < current_item: __a : int = point - 1 else: __a : str = point + 1 return None def __magic_name__ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : int ): # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __a : List[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 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 __magic_name__ ( _lowerCamelCase : Optional[Any] ): if collection != sorted(_lowerCamelCase ): raise ValueError("""Collection must be ascending sorted""" ) return True if __name__ == "__main__": import sys lowercase__ = 0 if debug == 1: lowercase__ = [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") lowercase__ = 67 lowercase__ = interpolation_search(collection, target) if result is not None: print(f'{target} found at positions: {result}') else: print("Not found")
715
"""simple docstring""" import torch from diffusers import DiffusionPipeline class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase ): '''simple docstring''' super().__init__() self.register_modules(unet=_lowercase , scheduler=_lowercase ) def __call__(self ): '''simple docstring''' __a : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __a : Optional[Any] = 1 __a : List[str] = self.unet(_lowercase , _lowercase ).sample __a : Union[str, Any] = self.scheduler.step(_lowercase , _lowercase , _lowercase ).prev_sample __a : Optional[int] = scheduler_output - scheduler_output + torch.ones_like(_lowercase ) return result
63
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "google/mobilenet_v2_1.4_224": "https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json", "google/mobilenet_v2_1.0_224": "https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json", "google/mobilenet_v2_0.75_160": "https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json", "google/mobilenet_v2_0.35_96": "https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "mobilenet_v2" def __init__(self , _lowercase=3 , _lowercase=224 , _lowercase=1.0 , _lowercase=8 , _lowercase=8 , _lowercase=6 , _lowercase=32 , _lowercase=True , _lowercase=True , _lowercase="relu6" , _lowercase=True , _lowercase=0.8 , _lowercase=0.02 , _lowercase=0.001 , _lowercase=255 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase ) if depth_multiplier <= 0: raise ValueError("""depth_multiplier must be greater than zero.""" ) __a : Optional[int] = num_channels __a : Union[str, Any] = image_size __a : List[str] = depth_multiplier __a : Optional[int] = depth_divisible_by __a : Dict = min_depth __a : List[str] = expand_ratio __a : Optional[Any] = output_stride __a : Tuple = first_layer_is_expansion __a : str = finegrained_output __a : str = hidden_act __a : Optional[Any] = tf_padding __a : Any = classifier_dropout_prob __a : List[str] = initializer_range __a : Tuple = layer_norm_eps __a : List[str] = semantic_loss_ignore_index class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = version.parse("1.11" ) @property def lowerCAmelCase__(self ): '''simple docstring''' return OrderedDict([("""pixel_values""", {0: """batch"""})] ) @property def lowerCAmelCase__(self ): '''simple docstring''' if self.task == "image-classification": return OrderedDict([("""logits""", {0: """batch"""})] ) else: return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 1e-4
716
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json", # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "vit_msn" def __init__(self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1e-06 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=True , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase ) __a : int = hidden_size __a : str = num_hidden_layers __a : str = num_attention_heads __a : Optional[Any] = intermediate_size __a : Union[str, Any] = hidden_act __a : Tuple = hidden_dropout_prob __a : Any = attention_probs_dropout_prob __a : List[Any] = initializer_range __a : Any = layer_norm_eps __a : Dict = image_size __a : List[Any] = patch_size __a : Dict = num_channels __a : Optional[Any] = qkv_bias
63
0
"""simple docstring""" from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record lowercase__ = "\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n" lowercase__ = "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n" lowercase__ = "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for 'record': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'prediction_text': the predicted answer text\n - for 'multirc': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question-answer pair as specified by the dataset\n - 'prediction': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for 'record': list of question-answers dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'answers': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for 'record':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1': F1 score\n - for 'multirc':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1_m': Per-question macro-F1 score\n - 'f1_a': Average F1 score over all answers\n - for 'axb':\n 'matthews_correlation': Matthew Correlation\n - for 'cb':\n - 'accuracy': Accuracy\n - 'f1': F1 score\n - for all others:\n - 'accuracy': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def __magic_name__ ( _lowerCamelCase : List[Any] , _lowerCamelCase : Optional[Any] ): return float((preds == labels).mean() ) def __magic_name__ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any]="binary" ): __a : Optional[Any] = simple_accuracy(_lowerCamelCase , _lowerCamelCase ) __a : Union[str, Any] = float(fa_score(y_true=_lowerCamelCase , y_pred=_lowerCamelCase , average=_lowerCamelCase ) ) return { "accuracy": acc, "f1": fa, } def __magic_name__ ( _lowerCamelCase : List[str] , _lowerCamelCase : Union[str, Any] ): __a : Dict = {} for id_pred, label in zip(_lowerCamelCase , _lowerCamelCase ): __a : Dict = F'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}''' __a : List[Any] = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: __a : Optional[int] = [(pred, label)] __a : Optional[int] = [], [] for question, preds_labels in question_map.items(): __a : Dict = zip(*_lowerCamelCase ) __a : str = fa_score(y_true=_lowerCamelCase , y_pred=_lowerCamelCase , average="""macro""" ) fas.append(_lowerCamelCase ) __a : str = int(sum(pred == label for pred, label in preds_labels ) == len(_lowerCamelCase ) ) ems.append(_lowerCamelCase ) __a : Dict = float(sum(_lowerCamelCase ) / len(_lowerCamelCase ) ) __a : Union[str, Any] = sum(_lowerCamelCase ) / len(_lowerCamelCase ) __a : List[Any] = float(fa_score(y_true=_lowerCamelCase , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def lowerCAmelCase__(self ): '''simple docstring''' if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def lowerCAmelCase__(self ): '''simple docstring''' if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_lowercase , _lowercase )} elif self.config_name == "cb": return acc_and_fa(_lowercase , _lowercase , fa_avg="""macro""" ) elif self.config_name == "record": __a : List[str] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] __a : List[Any] = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_lowercase , _lowercase )[0] elif self.config_name == "multirc": return evaluate_multirc(_lowercase , _lowercase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_lowercase , _lowercase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
717
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowercase__ = logging.get_logger(__name__) lowercase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRContextEncoderTokenizer class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRQuestionEncoderTokenizer lowercase__ = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) lowercase__ = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) lowercase__ = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ : def __call__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , **_lowercase , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) elif titles is None or texts is None: __a : str = titles if texts is None else texts return super().__call__( _lowercase , _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) __a : str = titles if not isinstance(_lowercase , _lowercase ) else [titles] __a : Optional[Any] = texts if not isinstance(_lowercase , _lowercase ) else [texts] __a : Tuple = len(_lowercase ) __a : Dict = questions if not isinstance(_lowercase , _lowercase ) else [questions] * n_passages assert len(_lowercase ) == len( _lowercase ), F'''There should be as many titles than texts but got {len(_lowercase )} titles and {len(_lowercase )} texts.''' __a : Optional[Any] = super().__call__(_lowercase , _lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : str = super().__call__(_lowercase , add_special_tokens=_lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : Union[str, Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowercase , _lowercase ) ] } if return_attention_mask is not False: __a : Optional[int] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __a : str = attention_mask return self.pad(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 16 , _lowercase = 64 , _lowercase = 4 , ): '''simple docstring''' __a : Union[str, Any] = reader_input["""input_ids"""] __a , __a , __a : Optional[int] = reader_output[:3] __a : int = len(_lowercase ) __a : Any = sorted(range(_lowercase ) , reverse=_lowercase , key=relevance_logits.__getitem__ ) __a : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __a : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __a : Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __a : int = sequence_ids.index(self.pad_token_id ) else: __a : Optional[Any] = len(_lowercase ) __a : List[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowercase , top_spans=_lowercase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowercase , start_index=_lowercase , end_index=_lowercase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowercase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' __a : Tuple = [] for start_index, start_score in enumerate(_lowercase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __a : str = sorted(_lowercase , key=lambda _lowercase : x[1] , reverse=_lowercase ) __a : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' __a : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowercase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = ["input_ids", "attention_mask"] _lowerCAmelCase = DPRReaderTokenizer
63
0
"""simple docstring""" lowercase__ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __magic_name__ ( ): __a : Dict = input("""Enter message: """ ) __a : Union[str, Any] = input("""Enter key [alphanumeric]: """ ) __a : Optional[Any] = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): __a : int = """encrypt""" __a : str = encrypt_message(_lowerCamelCase , _lowerCamelCase ) elif mode.lower().startswith("""d""" ): __a : Optional[Any] = """decrypt""" __a : Optional[Any] = decrypt_message(_lowerCamelCase , _lowerCamelCase ) print(F'''\n{mode.title()}ed message:''' ) print(_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : str ): return translate_message(_lowerCamelCase , _lowerCamelCase , """encrypt""" ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : str ): return translate_message(_lowerCamelCase , _lowerCamelCase , """decrypt""" ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : str ): __a : Optional[int] = [] __a : str = 0 __a : Union[str, Any] = key.upper() for symbol in message: __a : Dict = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(_lowerCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(_lowerCamelCase ): __a : Optional[int] = 0 else: translated.append(_lowerCamelCase ) return "".join(_lowerCamelCase ) if __name__ == "__main__": main()
718
"""simple docstring""" import os def __magic_name__ ( _lowerCamelCase : Dict ): __a : List[str] = len(grid[0] ) __a : int = len(_lowerCamelCase ) __a : Tuple = 0 __a : List[Any] = 0 __a : List[str] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_lowerCamelCase ): for j in range(n_rows - 3 ): __a : List[Any] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] __a : Tuple = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: __a : List[Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: __a : List[Any] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) __a : str = max( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if max_product > largest: __a : Optional[Any] = max_product return largest def __magic_name__ ( ): __a : Tuple = [] with open(os.path.dirname(_lowerCamelCase ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) __a : Tuple = [[int(_lowerCamelCase ) for i in grid[j]] for j in range(len(_lowerCamelCase ) )] return largest_product(_lowerCamelCase ) if __name__ == "__main__": print(solution())
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : int ): __a : list[list[str]] = [[] for _ in range(_lowerCamelCase )] __a : Any = key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_lowerCamelCase ) <= key: return input_string for position, character in enumerate(_lowerCamelCase ): __a : str = position % (lowest * 2) # puts it in bounds __a : Optional[Any] = min(_lowerCamelCase , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_lowerCamelCase ) __a : Dict = ["""""".join(_lowerCamelCase ) for row in temp_grid] __a : Union[str, Any] = """""".join(_lowerCamelCase ) return output_string def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : int ): __a : Tuple = [] __a : List[Any] = key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string __a : list[list[str]] = [[] for _ in range(_lowerCamelCase )] # generates template for position in range(len(_lowerCamelCase ) ): __a : List[Any] = position % (lowest * 2) # puts it in bounds __a : Tuple = min(_lowerCamelCase , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) __a : Tuple = 0 for row in temp_grid: # fills in the characters __a : Union[str, Any] = input_string[counter : counter + len(_lowerCamelCase )] grid.append(list(_lowerCamelCase ) ) counter += len(_lowerCamelCase ) __a : Dict = """""" # reads as zigzag for position in range(len(_lowerCamelCase ) ): __a : List[str] = position % (lowest * 2) # puts it in bounds __a : Optional[Any] = min(_lowerCamelCase , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __magic_name__ ( _lowerCamelCase : str ): __a : Tuple = {} for key_guess in range(1 , len(_lowerCamelCase ) ): # tries every key __a : Tuple = decrypt(_lowerCamelCase , _lowerCamelCase ) return results if __name__ == "__main__": import doctest doctest.testmod()
719
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 42 _lowerCAmelCase = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
63
0
"""simple docstring""" import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) lowercase__ = { "iou_prediction_head.layers.0": "iou_prediction_head.proj_in", "iou_prediction_head.layers.1": "iou_prediction_head.layers.0", "iou_prediction_head.layers.2": "iou_prediction_head.proj_out", "mask_decoder.output_upscaling.0": "mask_decoder.upscale_conv1", "mask_decoder.output_upscaling.1": "mask_decoder.upscale_layer_norm", "mask_decoder.output_upscaling.3": "mask_decoder.upscale_conv2", "mask_downscaling.0": "mask_embed.conv1", "mask_downscaling.1": "mask_embed.layer_norm1", "mask_downscaling.3": "mask_embed.conv2", "mask_downscaling.4": "mask_embed.layer_norm2", "mask_downscaling.6": "mask_embed.conv3", "point_embeddings": "point_embed", "pe_layer.positional_encoding_gaussian_matrix": "shared_embedding.positional_embedding", "image_encoder": "vision_encoder", "neck.0": "neck.conv1", "neck.1": "neck.layer_norm1", "neck.2": "neck.conv2", "neck.3": "neck.layer_norm2", "patch_embed.proj": "patch_embed.projection", ".norm": ".layer_norm", "blocks": "layers", } def __magic_name__ ( _lowerCamelCase : Any ): __a : List[str] = {} state_dict.pop("""pixel_mean""" , _lowerCamelCase ) state_dict.pop("""pixel_std""" , _lowerCamelCase ) __a : Any = r""".*.output_hypernetworks_mlps.(\d+).layers.(\d+).*""" for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: __a : str = key.replace(_lowerCamelCase , _lowerCamelCase ) if re.match(_lowerCamelCase , _lowerCamelCase ): __a : List[Any] = int(re.match(_lowerCamelCase , _lowerCamelCase ).group(2 ) ) if layer_nb == 0: __a : int = key.replace("""layers.0""" , """proj_in""" ) elif layer_nb == 1: __a : Union[str, Any] = key.replace("""layers.1""" , """layers.0""" ) elif layer_nb == 2: __a : Optional[int] = key.replace("""layers.2""" , """proj_out""" ) __a : Dict = value __a : Optional[int] = model_state_dict[ """prompt_encoder.shared_embedding.positional_embedding""" ] return model_state_dict def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Dict , _lowerCamelCase : Dict , _lowerCamelCase : int="ybelkada/segment-anything" ): __a : int = hf_hub_download(_lowerCamelCase , F'''checkpoints/{model_name}.pth''' ) if "sam_vit_b" in model_name: __a : Optional[int] = SamConfig() elif "sam_vit_l" in model_name: __a : Union[str, Any] = SamVisionConfig( hidden_size=1_0_2_4 , num_hidden_layers=2_4 , num_attention_heads=1_6 , global_attn_indexes=[5, 1_1, 1_7, 2_3] , ) __a : Optional[Any] = SamConfig( vision_config=_lowerCamelCase , ) elif "sam_vit_h" in model_name: __a : Optional[int] = SamVisionConfig( hidden_size=1_2_8_0 , num_hidden_layers=3_2 , num_attention_heads=1_6 , global_attn_indexes=[7, 1_5, 2_3, 3_1] , ) __a : Optional[int] = SamConfig( vision_config=_lowerCamelCase , ) __a : str = torch.load(_lowerCamelCase , map_location="""cpu""" ) __a : Dict = replace_keys(_lowerCamelCase ) __a : Any = SamImageProcessor() __a : Union[str, Any] = SamProcessor(image_processor=_lowerCamelCase ) __a : int = SamModel(_lowerCamelCase ) hf_model.load_state_dict(_lowerCamelCase ) __a : List[Any] = hf_model.to("""cuda""" ) __a : Tuple = """https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png""" __a : str = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw ).convert("""RGB""" ) __a : str = [[[4_0_0, 6_5_0]]] __a : Any = [[1]] __a : Optional[int] = processor(images=np.array(_lowerCamelCase ) , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): __a : Optional[Any] = hf_model(**_lowerCamelCase ) __a : Any = output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.5_79_89_02_51_15_96_68 __a : Tuple = processor( images=np.array(_lowerCamelCase ) , input_points=_lowerCamelCase , input_labels=_lowerCamelCase , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): __a : int = hf_model(**_lowerCamelCase ) __a : Any = output.iou_scores.squeeze() assert scores[-1].item() == 0.97_12_60_30_92_19_36_04 __a : Union[str, Any] = ((7_5, 2_7_5, 1_7_2_5, 8_5_0),) __a : Optional[int] = processor(images=np.array(_lowerCamelCase ) , input_boxes=_lowerCamelCase , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): __a : Optional[int] = hf_model(**_lowerCamelCase ) __a : Optional[int] = output.iou_scores.squeeze() assert scores[-1].item() == 0.86_86_01_56_05_92_65_14 # Test with 2 points and 1 image. __a : int = [[[4_0_0, 6_5_0], [8_0_0, 6_5_0]]] __a : str = [[1, 1]] __a : Dict = processor( images=np.array(_lowerCamelCase ) , input_points=_lowerCamelCase , input_labels=_lowerCamelCase , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): __a : Optional[int] = hf_model(**_lowerCamelCase ) __a : int = output.iou_scores.squeeze() assert scores[-1].item() == 0.99_36_04_77_92_43_46_92 if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() lowercase__ = ["sam_vit_b_01ec64", "sam_vit_h_4b8939", "sam_vit_l_0b3195"] parser.add_argument( "--model_name", default="sam_vit_h_4b8939", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) parser.add_argument( "--model_hub_id", default="ybelkada/segment-anything", choices=choices, type=str, help="Path to hf config.json of model to convert", ) lowercase__ = parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
720
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _lowerCAmelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCAmelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowerCAmelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowerCAmelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Optional[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __a : int = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : List[str] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __a : Optional[int] = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Tuple = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __a : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : Union[str, Any] = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __a : Optional[int] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __a : List[str] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = pipeline("""text-classification""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : Union[str, Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = pipeline("""text-classification""" , framework="""tf""" ) __a : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Tuple = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = TextClassificationPipeline(model=_lowercase , tokenizer=_lowercase ) return text_classifier, ["HuggingFace is in", "This is another test"] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __a : Union[str, Any] = """HuggingFace is in""" __a : List[str] = text_classifier(_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __a : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __a : Dict = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}, {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __a : Dict = text_classifier(_lowercase , top_k=_lowercase ) __a : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N, [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N] , ) __a : Dict = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __a : Any = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __a : Dict = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(_lowercase ): text_classifier(_lowercase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __a : Optional[int] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
63
0
"""simple docstring""" def __magic_name__ ( ): __a : Union[str, Any] = [3_1, 2_8, 3_1, 3_0, 3_1, 3_0, 3_1, 3_1, 3_0, 3_1, 3_0, 3_1] __a : List[Any] = 6 __a : List[Any] = 1 __a : Optional[Any] = 1_9_0_1 __a : Union[str, Any] = 0 while year < 2_0_0_1: day += 7 if (year % 4 == 0 and year % 1_0_0 != 0) or (year % 4_0_0 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 __a : Optional[Any] = day - days_per_month[month - 2] elif day > 2_9 and month == 2: month += 1 __a : Optional[Any] = day - 2_9 else: if day > days_per_month[month - 1]: month += 1 __a : List[str] = day - days_per_month[month - 2] if month > 1_2: year += 1 __a : Optional[Any] = 1 if year < 2_0_0_1 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
721
"""simple docstring""" import unittest from knapsack import knapsack as k class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : str = 0 __a : Optional[Any] = [0] __a : int = [0] __a : str = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) __a : int = [60] __a : Union[str, Any] = [10] __a : Tuple = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = 3 __a : str = [1, 2, 3] __a : Optional[Any] = [3, 2, 1] __a : int = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 50 __a : Tuple = [60, 100, 120] __a : List[str] = [10, 20, 30] __a : Union[str, Any] = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 ) if __name__ == "__main__": unittest.main()
63
0
"""simple docstring""" from __future__ import annotations def __magic_name__ ( _lowerCamelCase : tuple[int, int] , _lowerCamelCase : int ): __a : Tuple = position __a : Any = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] __a : List[Any] = [] for position in positions: __a : int = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(_lowerCamelCase ) return permissible_positions def __magic_name__ ( _lowerCamelCase : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def __magic_name__ ( _lowerCamelCase : list[list[int]] , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : int ): if is_complete(_lowerCamelCase ): return True for position in get_valid_pos(_lowerCamelCase , len(_lowerCamelCase ) ): __a : int = position if board[y][x] == 0: __a : List[str] = curr + 1 if open_knight_tour_helper(_lowerCamelCase , _lowerCamelCase , curr + 1 ): return True __a : str = 0 return False def __magic_name__ ( _lowerCamelCase : int ): __a : Dict = [[0 for i in range(_lowerCamelCase )] for j in range(_lowerCamelCase )] for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): __a : List[Any] = 1 if open_knight_tour_helper(_lowerCamelCase , (i, j) , 1 ): return board __a : List[str] = 0 __a : List[str] = F'''Open Kight Tour cannot be performed on a board of size {n}''' raise ValueError(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
700
"""simple docstring""" from manim import * class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = Rectangle(height=0.5 , width=0.5 ) __a : Union[str, Any] = Rectangle(height=0.25 , width=0.25 ) __a : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a : Dict = [mem.copy() for i in range(6 )] __a : str = [mem.copy() for i in range(6 )] __a : Tuple = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Union[str, Any] = Text("""CPU""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(4 )] __a : Dict = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = Text("""GPU""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) gpu.move_to([-1, -1, 0] ) self.add(_lowercase ) __a : List[Any] = [mem.copy() for i in range(6 )] __a : Any = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Optional[Any] = Text("""Model""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) model.move_to([3, -1.0, 0] ) self.add(_lowercase ) __a : Tuple = [] __a : Tuple = [] __a : Optional[int] = [] for i, rect in enumerate(_lowercase ): rect.set_stroke(_lowercase ) __a : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_lowercase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowercase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_lowercase , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_lowercase , buff=0.0 ) self.add(_lowercase ) model_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase , *_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(6 )] __a : Union[str, Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Any = Text("""Loaded Checkpoint""" , font_size=24 ) __a : str = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) checkpoint.move_to([3, 0.5, 0] ) self.add(_lowercase ) __a : Dict = [] __a : int = [] for i, rect in enumerate(_lowercase ): __a : List[str] = fill.copy().set_fill(_lowercase , opacity=0.7 ) target.move_to(_lowercase ) ckpt_arr.append(_lowercase ) __a : Union[str, Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase ) __a : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a : List[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_lowercase , _lowercase ) __a : str = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_lowercase ) __a : Optional[int] = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) __a : List[Any] = [meta_mem.copy() for i in range(6 )] __a : Optional[int] = [meta_mem.copy() for i in range(6 )] __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Tuple = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Dict = Text("""Disk""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_lowercase , run_time=3 ) , Write(_lowercase , run_time=1 ) , Create(_lowercase , run_time=1 ) ) __a : Optional[Any] = [] for i, rect in enumerate(_lowercase ): __a : List[str] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_lowercase , run_time=1.5 ) ) self.play(*_lowercase ) self.play(FadeOut(_lowercase ) ) __a : List[str] = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_lowercase , run_time=3 ) ) self.play( FadeOut(_lowercase , _lowercase , *_lowercase , *_lowercase ) , ) self.wait()
63
0
"""simple docstring""" from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 4_2 # [batch_size x 3] _lowerCAmelCase = 4_2 # [batch_size x 3] _lowerCAmelCase = 4_2 # [batch_size x 3] _lowerCAmelCase = 4_2 # [batch_size x 3] _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 def lowerCAmelCase__(self ): '''simple docstring''' assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def lowerCAmelCase__(self ): '''simple docstring''' return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def lowerCAmelCase__(self ): '''simple docstring''' return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = torch.arange(self.height * self.width ) __a : Tuple = torch.stack( [ pixel_indices % self.width, torch.div(_lowercase , self.width , rounding_mode="""trunc""" ), ] , axis=1 , ) return coords @property def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.shape __a : int = int(np.prod(_lowercase ) ) __a : Union[str, Any] = self.get_image_coords() __a : List[Any] = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a : List[str] = self.get_camera_rays(_lowercase ) __a : Union[str, Any] = rays.view(_lowercase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : str = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a : List[str] = coords.view(_lowercase , -1 , 2 ) __a : List[Any] = self.resolution() __a : List[Any] = self.fov() __a : List[str] = (flat.float() / (res - 1)) * 2 - 1 __a : int = fracs * torch.tan(fov / 2 ) __a : Optional[int] = fracs.view(_lowercase , -1 , 2 ) __a : Optional[int] = ( self.z.view(_lowercase , 1 , 3 ) + self.x.view(_lowercase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(_lowercase , 1 , 3 ) * fracs[:, :, 1:] ) __a : List[str] = directions / directions.norm(dim=-1 , keepdim=_lowercase ) __a : int = torch.stack( [ torch.broadcast_to(self.origin.view(_lowercase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(_lowercase , *_lowercase , 2 , 3 ) def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=_lowercase , height=_lowercase , x_fov=self.x_fov , y_fov=self.y_fov , ) def __magic_name__ ( _lowerCamelCase : int ): __a : int = [] __a : str = [] __a : Optional[int] = [] __a : Optional[Any] = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a : str = np.array([np.sin(_lowerCamelCase ), np.cos(_lowerCamelCase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a : Any = -z * 4 __a : Union[str, Any] = np.array([np.cos(_lowerCamelCase ), -np.sin(_lowerCamelCase ), 0.0] ) __a : Dict = np.cross(_lowerCamelCase , _lowerCamelCase ) origins.append(_lowerCamelCase ) xs.append(_lowerCamelCase ) ys.append(_lowerCamelCase ) zs.append(_lowerCamelCase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(_lowerCamelCase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(_lowerCamelCase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(_lowerCamelCase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(_lowerCamelCase , axis=0 ) ).float() , width=_lowerCamelCase , height=_lowerCamelCase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(_lowerCamelCase )) , )
701
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float(moles / volume ) * nfactor ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (volume) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (pressure) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((pressure * volume) / (0.08_21 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , *_lowercase , **_lowercase ): '''simple docstring''' warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , _lowercase , ) super().__init__(*_lowercase , **_lowercase )
702
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : list[int] ): if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) __a : Any = sum(_lowerCamelCase ) / len(_lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowercase__ = logging.get_logger(__name__) def __magic_name__ ( _lowerCamelCase : int ): __a : List[str] = DPTConfig() if "large" in checkpoint_url: __a : Dict = 1_0_2_4 __a : Optional[Any] = 4_0_9_6 __a : Dict = 2_4 __a : Dict = 1_6 __a : List[str] = [5, 1_1, 1_7, 2_3] __a : Optional[Any] = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] __a : List[Any] = (1, 3_8_4, 3_8_4) if "ade" in checkpoint_url: __a : Tuple = True __a : List[Any] = 1_5_0 __a : Optional[int] = """huggingface/label-files""" __a : Union[str, Any] = """ade20k-id2label.json""" __a : Dict = json.load(open(cached_download(hf_hub_url(_lowerCamelCase , _lowerCamelCase , repo_type="""dataset""" ) ) , """r""" ) ) __a : Optional[int] = {int(_lowerCamelCase ): v for k, v in idalabel.items()} __a : str = idalabel __a : Dict = {v: k for k, v in idalabel.items()} __a : Union[str, Any] = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def __magic_name__ ( _lowerCamelCase : Tuple ): __a : Union[str, Any] = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : str ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): __a : str = name.replace("""pretrained.model""" , """dpt.encoder""" ) if "pretrained.model" in name: __a : Dict = name.replace("""pretrained.model""" , """dpt.embeddings""" ) if "patch_embed" in name: __a : Optional[int] = name.replace("""patch_embed""" , """patch_embeddings""" ) if "pos_embed" in name: __a : Dict = name.replace("""pos_embed""" , """position_embeddings""" ) if "attn.proj" in name: __a : str = name.replace("""attn.proj""" , """attention.output.dense""" ) if "proj" in name and "project" not in name: __a : Optional[int] = name.replace("""proj""" , """projection""" ) if "blocks" in name: __a : Dict = name.replace("""blocks""" , """layer""" ) if "mlp.fc1" in name: __a : List[str] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __a : Any = name.replace("""mlp.fc2""" , """output.dense""" ) if "norm1" in name: __a : List[str] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __a : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "scratch.output_conv" in name: __a : str = name.replace("""scratch.output_conv""" , """head""" ) if "scratch" in name: __a : Dict = name.replace("""scratch""" , """neck""" ) if "layer1_rn" in name: __a : Tuple = name.replace("""layer1_rn""" , """convs.0""" ) if "layer2_rn" in name: __a : List[str] = name.replace("""layer2_rn""" , """convs.1""" ) if "layer3_rn" in name: __a : Union[str, Any] = name.replace("""layer3_rn""" , """convs.2""" ) if "layer4_rn" in name: __a : List[str] = name.replace("""layer4_rn""" , """convs.3""" ) if "refinenet" in name: __a : List[Any] = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 __a : int = name.replace(F'''refinenet{layer_idx}''' , F'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: __a : str = name.replace("""out_conv""" , """projection""" ) if "resConfUnit1" in name: __a : str = name.replace("""resConfUnit1""" , """residual_layer1""" ) if "resConfUnit2" in name: __a : Any = name.replace("""resConfUnit2""" , """residual_layer2""" ) if "conv1" in name: __a : str = name.replace("""conv1""" , """convolution1""" ) if "conv2" in name: __a : str = name.replace("""conv2""" , """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: __a : Any = name.replace("""pretrained.act_postprocess1.0.project.0""" , """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: __a : Any = name.replace("""pretrained.act_postprocess2.0.project.0""" , """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: __a : int = name.replace("""pretrained.act_postprocess3.0.project.0""" , """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: __a : List[Any] = name.replace("""pretrained.act_postprocess4.0.project.0""" , """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: __a : Union[str, Any] = name.replace("""pretrained.act_postprocess1.3""" , """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: __a : Union[str, Any] = name.replace("""pretrained.act_postprocess1.4""" , """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: __a : Optional[int] = name.replace("""pretrained.act_postprocess2.3""" , """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: __a : Union[str, Any] = name.replace("""pretrained.act_postprocess2.4""" , """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: __a : List[Any] = name.replace("""pretrained.act_postprocess3.3""" , """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: __a : List[str] = name.replace("""pretrained.act_postprocess4.3""" , """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: __a : Dict = name.replace("""pretrained.act_postprocess4.4""" , """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: __a : List[str] = name.replace("""pretrained""" , """dpt""" ) if "bn" in name: __a : Optional[Any] = name.replace("""bn""" , """batch_norm""" ) if "head" in name: __a : str = name.replace("""head""" , """head.head""" ) if "encoder.norm" in name: __a : Optional[Any] = name.replace("""encoder.norm""" , """layernorm""" ) if "auxlayer" in name: __a : Tuple = name.replace("""auxlayer""" , """auxiliary_head.head""" ) return name def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Optional[int] ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __a : Dict = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) __a : List[str] = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __a : str = in_proj_weight[: config.hidden_size, :] __a : Dict = in_proj_bias[: config.hidden_size] __a : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __a : Union[str, Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __a : int = in_proj_weight[ -config.hidden_size :, : ] __a : Tuple = in_proj_bias[-config.hidden_size :] def __magic_name__ ( ): __a : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" __a : Tuple = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw ) return im @torch.no_grad() def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : List[Any] ): __a : Optional[int] = get_dpt_config(_lowerCamelCase ) # load original state_dict from URL __a : Optional[Any] = torch.hub.load_state_dict_from_url(_lowerCamelCase , map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(_lowerCamelCase ) # rename keys for key in state_dict.copy().keys(): __a : Dict = state_dict.pop(_lowerCamelCase ) __a : Dict = val # read in qkv matrices read_in_q_k_v(_lowerCamelCase , _lowerCamelCase ) # load HuggingFace model __a : int = DPTForSemanticSegmentation(_lowerCamelCase ) if """ade""" in checkpoint_url else DPTForDepthEstimation(_lowerCamelCase ) model.load_state_dict(_lowerCamelCase ) model.eval() # Check outputs on an image __a : int = 4_8_0 if """ade""" in checkpoint_url else 3_8_4 __a : str = DPTImageProcessor(size=_lowerCamelCase ) __a : Dict = prepare_img() __a : List[Any] = image_processor(_lowerCamelCase , return_tensors="""pt""" ) # forward pass __a : Union[str, Any] = model(**_lowerCamelCase ).logits if """ade""" in checkpoint_url else model(**_lowerCamelCase ).predicted_depth # Assert logits __a : Optional[Any] = torch.tensor([[6.31_99, 6.36_29, 6.41_48], [6.38_50, 6.36_15, 6.41_66], [6.35_19, 6.31_76, 6.35_75]] ) if "ade" in checkpoint_url: __a : Optional[Any] = torch.tensor([[4.04_80, 4.24_20, 4.43_60], [4.31_24, 4.56_93, 4.82_61], [4.57_68, 4.89_65, 5.21_63]] ) assert outputs.shape == torch.Size(_lowerCamelCase ) assert ( torch.allclose(outputs[0, 0, :3, :3] , _lowerCamelCase , atol=1E-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3] , _lowerCamelCase ) ) Path(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(_lowerCamelCase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_lowerCamelCase ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(_lowerCamelCase , _lowerCamelCase ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=_lowerCamelCase , ) image_processor.push_to_hub( repo_path_or_name=Path(_lowerCamelCase , _lowerCamelCase ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=_lowerCamelCase , ) if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", type=str, help="URL of the original DPT checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", ) parser.add_argument( "--model_name", default="dpt-large", type=str, help="Name of the model, in case you're pushing to the hub.", ) lowercase__ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
703
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math.sqrt(_lowerCamelCase ) __a : Any = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): __a : Any = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float ): # Creates a gaussian kernel of given dimension. __a : int = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowerCamelCase ): for j in range(0 , _lowerCamelCase ): __a : Any = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int , ): __a : Tuple = np.zeros(img.shape ) __a : Optional[int] = get_gauss_kernel(_lowerCamelCase , _lowerCamelCase ) __a , __a : int = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): __a : List[str] = get_slice(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Any = img_s - img_s[kernel_size // 2, kernel_size // 2] __a : Optional[Any] = vec_gaussian(_lowerCamelCase , _lowerCamelCase ) __a : Optional[Any] = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Any = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Tuple = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) __a : Optional[Any] = val return imga def __magic_name__ ( _lowerCamelCase : list ): __a : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" __a : Union[str, Any] = float(args[2] ) if args[2:] else 1.0 __a : Optional[int] = float(args[3] ) if args[3:] else 1.0 if args[4:]: __a : Any = int(args[4] ) __a : Any = kernel_size + abs(kernel_size % 2 - 1 ) else: __a : Optional[int] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": lowercase__ , lowercase__ , lowercase__ , lowercase__ = parse_args(sys.argv) lowercase__ = cva.imread(filename, 0) cva.imshow("input image", img) lowercase__ = img / 255 lowercase__ = out.astype("float32") lowercase__ = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) lowercase__ = out * 255 lowercase__ = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
63
0
"""simple docstring""" import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput lowercase__ = "scheduler_config.json" class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 1 _lowerCAmelCase = 2 _lowerCAmelCase = 3 _lowerCAmelCase = 4 _lowerCAmelCase = 5 @dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 4_2 class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = SCHEDULER_CONFIG_NAME _lowerCAmelCase = ["dtype"] _lowerCAmelCase = [] _lowerCAmelCase = True @classmethod def lowerCAmelCase__(cls , _lowercase = None , _lowercase = None , _lowercase=False , **_lowercase , ): '''simple docstring''' __a : Optional[Any] = cls.load_config( pretrained_model_name_or_path=_lowercase , subfolder=_lowercase , return_unused_kwargs=_lowercase , **_lowercase , ) __a : List[Any] = cls.from_config(_lowercase , return_unused_kwargs=_lowercase , **_lowercase ) if hasattr(_lowercase , """create_state""" ) and getattr(_lowercase , """has_state""" , _lowercase ): __a : str = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def lowerCAmelCase__(self , _lowercase , _lowercase = False , **_lowercase ): '''simple docstring''' self.save_config(save_directory=_lowercase , push_to_hub=_lowercase , **_lowercase ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self._get_compatibles() @classmethod def lowerCAmelCase__(cls ): '''simple docstring''' __a : Any = list(set([cls.__name__] + cls._compatibles ) ) __a : str = importlib.import_module(__name__.split(""".""" )[0] ) __a : Union[str, Any] = [ getattr(_lowercase , _lowercase ) for c in compatible_classes_str if hasattr(_lowercase , _lowercase ) ] return compatible_classes def __magic_name__ ( _lowerCamelCase : jnp.ndarray , _lowerCamelCase : Tuple[int] ): assert len(_lowerCamelCase ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(_lowerCamelCase ) - x.ndim) ) , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int=0.9_99 , _lowerCamelCase : int=jnp.floataa ): def alpha_bar(_lowerCamelCase : List[Any] ): return math.cos((time_step + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 __a : str = [] for i in range(_lowerCamelCase ): __a : List[str] = i / num_diffusion_timesteps __a : List[Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(_lowerCamelCase ) / alpha_bar(_lowerCamelCase ) , _lowerCamelCase ) ) return jnp.array(_lowerCamelCase , dtype=_lowerCamelCase ) @flax.struct.dataclass class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 @classmethod def lowerCAmelCase__(cls , _lowercase ): '''simple docstring''' __a : int = scheduler.config if config.trained_betas is not None: __a : Tuple = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": __a : List[str] = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a : str = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a : Tuple = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( F'''beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}''' ) __a : List[Any] = 1.0 - betas __a : Union[str, Any] = jnp.cumprod(_lowercase , axis=0 ) return cls( alphas=_lowercase , betas=_lowercase , alphas_cumprod=_lowercase , ) def __magic_name__ ( _lowerCamelCase : CommonSchedulerState , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray ): __a : List[str] = state.alphas_cumprod __a : Dict = alphas_cumprod[timesteps] ** 0.5 __a : Any = sqrt_alpha_prod.flatten() __a : Union[str, Any] = broadcast_to_shape_from_left(_lowerCamelCase , original_samples.shape ) __a : Tuple = (1 - alphas_cumprod[timesteps]) ** 0.5 __a : int = sqrt_one_minus_alpha_prod.flatten() __a : int = broadcast_to_shape_from_left(_lowerCamelCase , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def __magic_name__ ( _lowerCamelCase : CommonSchedulerState , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray ): __a : Union[str, Any] = get_sqrt_alpha_prod(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Tuple = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def __magic_name__ ( _lowerCamelCase : CommonSchedulerState , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray ): __a : Union[str, Any] = get_sqrt_alpha_prod(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : int = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
704
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __magic_name__ ( ): __a : Dict = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 2_0, """a """ * 3_0, """b """ * 7], } __a : Optional[Any] = Dataset.from_dict(_lowerCamelCase ) return dataset class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = get_dataset() __a : List[Any] = make_duplicate_clusters(_lowercase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = get_dataset() __a , __a : Optional[Any] = deduplicate_dataset(_lowercase ) self.assertEqual(len(_lowercase ) , 2 ) print(_lowercase ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , _lowercase )
63
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase__ = random.Random() def __magic_name__ ( _lowerCamelCase : Dict , _lowerCamelCase : List[str]=1.0 , _lowerCamelCase : List[str]=None , _lowerCamelCase : List[Any]=None ): if rng is None: __a : Dict = global_rng __a : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__(self , _lowercase , _lowercase=7 , _lowercase=400 , _lowercase=2000 , _lowercase=1 , _lowercase=0.0 , _lowercase=16000 , _lowercase=True , _lowercase=True , ): '''simple docstring''' __a : Optional[Any] = parent __a : str = batch_size __a : Optional[Any] = min_seq_length __a : str = max_seq_length __a : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __a : List[Any] = feature_size __a : Optional[int] = padding_value __a : Dict = sampling_rate __a : Any = return_attention_mask __a : Optional[int] = do_normalize def lowerCAmelCase__(self ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCAmelCase__(self , _lowercase=False , _lowercase=False ): '''simple docstring''' def _flatten(_lowercase ): return list(itertools.chain(*_lowercase ) ) if equal_length: __a : List[str] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __a : str = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __a : Dict = [np.asarray(_lowercase ) for x in speech_inputs] return speech_inputs class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = WavaVecaFeatureExtractor def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = WavaVecaFeatureExtractionTester(self ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' self.assertTrue(np.all(np.mean(_lowercase , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(_lowercase , axis=0 ) - 1 ) < 1e-3 ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __a : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __a : str = [np.asarray(_lowercase ) for speech_input in speech_inputs] # Test not batched input __a : int = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values __a : List[Any] = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(_lowercase , _lowercase , atol=1e-3 ) ) # Test batched __a : Optional[Any] = feat_extract(_lowercase , return_tensors="""np""" ).input_values __a : Optional[Any] = feat_extract(_lowercase , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(_lowercase , _lowercase ): self.assertTrue(np.allclose(_lowercase , _lowercase , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __a : Optional[int] = [floats_list((1, x) )[0] for x in (800, 800, 800)] __a : Dict = np.asarray(_lowercase ) __a : List[str] = feat_extract(_lowercase , return_tensors="""np""" ).input_values __a : Union[str, Any] = feat_extract(_lowercase , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(_lowercase , _lowercase ): self.assertTrue(np.allclose(_lowercase , _lowercase , atol=1e-3 ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __a : Optional[int] = ["""longest""", """max_length""", """do_not_pad"""] __a : int = [None, 1600, None] for max_length, padding in zip(_lowercase , _lowercase ): __a : Optional[int] = feat_extract(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors="""np""" ) __a : List[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : Optional[int] = range(800 , 1400 , 200 ) __a : Optional[Any] = [floats_list((1, x) )[0] for x in lengths] __a : Any = ["""longest""", """max_length""", """do_not_pad"""] __a : Any = [None, 1600, None] for max_length, padding in zip(_lowercase , _lowercase ): __a : Dict = feat_extract(_lowercase , max_length=_lowercase , padding=_lowercase ) __a : str = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __a : Dict = feat_extract( _lowercase , truncation=_lowercase , max_length=1000 , padding="""max_length""" , return_tensors="""np""" ) __a : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __a : Union[str, Any] = feat_extract( _lowercase , truncation=_lowercase , max_length=1000 , padding="""longest""" , return_tensors="""np""" ) __a : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) __a : List[str] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] __a : Union[str, Any] = feat_extract( _lowercase , truncation=_lowercase , max_length=2000 , padding="""longest""" , return_tensors="""np""" ) __a : str = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __a : List[str] = np.random.rand(100 ).astype(np.floataa ) __a : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __a : List[Any] = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __a : Dict = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: __a : Dict = WavaVecaConfig.from_pretrained(_lowercase ) __a : Any = WavaVecaFeatureExtractor.from_pretrained(_lowercase ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == """layer""" )
705
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available lowercase__ = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase=2 , _lowercase=32 , _lowercase=16 , _lowercase=3 , _lowercase=True , _lowercase=True , _lowercase=32 , _lowercase=4 , _lowercase=[0, 1, 2, 3] , _lowercase=4 , _lowercase=37 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=3 , _lowercase=[1, 384, 24, 24] , _lowercase=True , _lowercase=None , ): '''simple docstring''' __a : Optional[Any] = parent __a : List[Any] = batch_size __a : Tuple = image_size __a : Union[str, Any] = patch_size __a : Tuple = num_channels __a : Dict = is_training __a : str = use_labels __a : List[Any] = hidden_size __a : Dict = num_hidden_layers __a : str = backbone_out_indices __a : List[str] = num_attention_heads __a : Dict = intermediate_size __a : Union[str, Any] = hidden_act __a : Any = hidden_dropout_prob __a : Tuple = attention_probs_dropout_prob __a : Any = initializer_range __a : Optional[Any] = num_labels __a : Dict = backbone_featmap_shape __a : List[Any] = scope __a : List[str] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) __a : str = (image_size // patch_size) ** 2 __a : List[Any] = num_patches + 1 def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Optional[Any] = None if self.use_labels: __a : Optional[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a : Optional[int] = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' __a : int = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [96, 192, 384, 768], """num_groups""": 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , 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=_lowercase , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=_lowercase , backbone_featmap_shape=self.backbone_featmap_shape , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[int] = DPTModel(config=_lowercase ) model.to(_lowercase ) model.eval() __a : Union[str, Any] = model(_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : str = self.num_labels __a : Optional[int] = DPTForDepthEstimation(_lowercase ) model.to(_lowercase ) model.eval() __a : int = model(_lowercase ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = self.num_labels __a : List[Any] = DPTForSemanticSegmentation(_lowercase ) model.to(_lowercase ) model.eval() __a : Union[str, Any] = model(_lowercase , labels=_lowercase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : str = self.prepare_config_and_inputs() __a : List[str] = config_and_inputs __a : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () _lowerCAmelCase = ( { "depth-estimation": DPTForDepthEstimation, "feature-extraction": DPTModel, "image-segmentation": DPTForSemanticSegmentation, } if is_torch_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = DPTModelTester(self ) __a : Optional[int] = ConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(_lowercase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowercase , nn.Linear ) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : str = model_class(_lowercase ) __a : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[int] = [*signature.parameters.keys()] __a : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() __a : Any = True if model_class in get_values(_lowercase ): continue __a : List[Any] = model_class(_lowercase ) model.to(_lowercase ) model.train() __a : Optional[Any] = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) __a : str = model(**_lowercase ).loss loss.backward() def lowerCAmelCase__(self ): '''simple docstring''' for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue __a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __a : List[str] = False __a : Dict = True if model_class in get_values(_lowercase ) or not model_class.supports_gradient_checkpointing: continue __a : Optional[Any] = model_class(_lowercase ) model.to(_lowercase ) model.gradient_checkpointing_enable() model.train() __a : int = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) __a : Optional[int] = model(**_lowercase ).loss loss.backward() def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() __a : Optional[int] = _config_zero_init(_lowercase ) for model_class in self.all_model_classes: __a : str = model_class(config=_lowercase ) # Skip the check for the backbone __a : str = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": __a : List[str] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: __a : List[str] = DPTModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __a : Dict = """add""" with self.assertRaises(_lowercase ): __a : Union[str, Any] = DPTForDepthEstimation(_lowercase ) def __magic_name__ ( ): __a : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) __a : List[str] = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(_lowercase ) __a : Dict = prepare_img() __a : List[Any] = image_processor(images=_lowercase , return_tensors="""pt""" ).to(_lowercase ) # forward pass with torch.no_grad(): __a : Dict = model(**_lowercase ) __a : Tuple = outputs.predicted_depth # verify the predicted depth __a : Dict = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , _lowercase ) __a : List[str] = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(_lowercase ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , _lowercase , atol=1e-4 ) )
706
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "linear" _lowerCAmelCase = "cosine" _lowerCAmelCase = "cosine_with_restarts" _lowerCAmelCase = "polynomial" _lowerCAmelCase = "constant" _lowerCAmelCase = "constant_with_warmup" _lowerCAmelCase = "piecewise_constant" def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int = -1 ): return LambdaLR(_lowerCamelCase , lambda _lowerCamelCase : 1 , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1.0 , _lowerCamelCase ) ) return 1.0 return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : str , _lowerCamelCase : int = -1 ): __a : Optional[int] = {} __a : Any = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __a , __a : int = rule_str.split(""":""" ) __a : Optional[int] = int(_lowerCamelCase ) __a : str = float(_lowerCamelCase ) __a : int = value __a : Dict = float(rule_list[-1] ) def create_rules_function(_lowerCamelCase : str , _lowerCamelCase : Tuple ): def rule_func(_lowerCamelCase : int ) -> float: __a : Optional[Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(_lowerCamelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __a : Optional[int] = create_rules_function(_lowerCamelCase , _lowerCamelCase ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : str=-1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0.5 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Any ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(_lowerCamelCase ) * 2.0 * progress )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int = 1 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Optional[int] ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(_lowerCamelCase ) * progress) % 1.0) )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]=1E-7 , _lowerCamelCase : Optional[int]=1.0 , _lowerCamelCase : Optional[int]=-1 ): __a : Union[str, Any] = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __a : Tuple = lr_init - lr_end __a : int = num_training_steps - num_warmup_steps __a : Optional[int] = 1 - (current_step - num_warmup_steps) / decay_steps __a : List[str] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __magic_name__ ( _lowerCamelCase : Union[str, SchedulerType] , _lowerCamelCase : Optimizer , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 1 , _lowerCamelCase : float = 1.0 , _lowerCamelCase : int = -1 , ): __a : int = SchedulerType(_lowerCamelCase ) __a : Optional[int] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(_lowerCamelCase , last_epoch=_lowerCamelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(_lowerCamelCase , step_rules=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(_lowerCamelCase , num_warmup_steps=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , num_cycles=_lowerCamelCase , last_epoch=_lowerCamelCase , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , power=_lowerCamelCase , last_epoch=_lowerCamelCase , ) return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , last_epoch=_lowerCamelCase )
63
0
"""simple docstring""" from collections.abc import Sequence def __magic_name__ ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : bool = False ): if not arr: return 0 __a : Optional[int] = 0 if allow_empty_subarrays else float("""-inf""" ) __a : Union[str, Any] = 0.0 for num in arr: __a : Union[str, Any] = max(0 if allow_empty_subarrays else num , curr_sum + num ) __a : Any = max(_lowerCamelCase , _lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase__ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f'{max_subarray_sum(nums) = }')
707
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=False ): __a : Dict = OmegaConf.load(_lowerCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_lowerCamelCase ) ) ) return config def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : int=None ): if conf_path is None: __a : str = """./model_checkpoints/vqgan_only.yaml""" __a : List[Any] = load_config(_lowerCamelCase , display=_lowerCamelCase ) __a : Dict = VQModel(**config.model.params ) if ckpt_path is None: __a : List[Any] = """./model_checkpoints/vqgan_only.pt""" __a : Tuple = torch.load(_lowerCamelCase , map_location=_lowerCamelCase ) if ".ckpt" in ckpt_path: __a : List[str] = sd["""state_dict"""] model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase ) model.to(_lowerCamelCase ) del sd return model def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : List[str] ): __a , __a , __a : Tuple = model.encode(_lowerCamelCase ) print(F'''VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}''' ) __a : Union[str, Any] = model.decode(_lowerCamelCase ) return xrec def __magic_name__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any]=False ): __a , __a : Optional[Any] = string.rsplit(""".""" , 1 ) if reload: __a : Optional[Any] = importlib.import_module(_lowerCamelCase ) importlib.reload(_lowerCamelCase ) return getattr(importlib.import_module(_lowerCamelCase , package=_lowerCamelCase ) , cls ) def __magic_name__ ( _lowerCamelCase : Any ): if "target" not in config: raise KeyError("""Expected key `target` to instantiate.""" ) return get_obj_from_str(config["""target"""] )(**config.get("""params""" , {} ) ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Dict , _lowerCamelCase : int=True , _lowerCamelCase : int=True ): __a : Union[str, Any] = instantiate_from_config(_lowerCamelCase ) if sd is not None: model.load_state_dict(_lowerCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : int ): # load the specified checkpoint if ckpt: __a : List[str] = torch.load(_lowerCamelCase , map_location="""cpu""" ) __a : Any = pl_sd["""global_step"""] print(F'''loaded model from global step {global_step}.''' ) else: __a : List[Any] = {"""state_dict""": None} __a : Any = None __a : Union[str, Any] = load_model_from_config(config.model , pl_sd["""state_dict"""] , gpu=_lowerCamelCase , eval_mode=_lowerCamelCase )["""model"""] return model, global_step
63
0
"""simple docstring""" from itertools import product def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int ): __a : Dict = sides_number __a : Optional[Any] = max_face_number * dice_number __a : str = [0] * (max_total + 1) __a : Optional[int] = 1 __a : List[Any] = range(_lowerCamelCase , max_face_number + 1 ) for dice_numbers in product(_lowerCamelCase , repeat=_lowerCamelCase ): __a : List[Any] = sum(_lowerCamelCase ) totals_frequencies[total] += 1 return totals_frequencies def __magic_name__ ( ): __a : Optional[Any] = total_frequency_distribution( sides_number=4 , dice_number=9 ) __a : Optional[int] = total_frequency_distribution( sides_number=6 , dice_number=6 ) __a : Optional[Any] = 0 __a : Any = 9 __a : Union[str, Any] = 4 * 9 __a : Optional[Any] = 6 for peter_total in range(_lowerCamelCase , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) __a : Union[str, Any] = (4**9) * (6**6) __a : List[str] = peter_wins_count / total_games_number __a : Dict = round(_lowerCamelCase , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(f'{solution() = }')
708
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase__ = { "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = ["LlamaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "LlamaForCausalLM", "LlamaModel", "LlamaPreTrainedModel", "LlamaForSequenceClassification", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : int = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) __a : int = { """input_ids""": tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]] , dtype=tf.intaa ), # "My dog is cute" """attention_mask""": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } __a : str = model(_lowercase )["""last_hidden_state"""] __a : Tuple = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , _lowercase ) # compare the actual values for a slice. __a : Union[str, Any] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
709
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "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 SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "unispeech" def __init__(self , _lowercase=32 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=1e-5 , _lowercase="group" , _lowercase="gelu" , _lowercase=(512, 512, 512, 512, 512, 512, 512) , _lowercase=(5, 2, 2, 2, 2, 2, 2) , _lowercase=(10, 3, 3, 3, 3, 2, 2) , _lowercase=False , _lowercase=128 , _lowercase=16 , _lowercase=False , _lowercase=True , _lowercase=0.05 , _lowercase=10 , _lowercase=2 , _lowercase=0.0 , _lowercase=10 , _lowercase=0 , _lowercase=320 , _lowercase=2 , _lowercase=0.1 , _lowercase=100 , _lowercase=256 , _lowercase=256 , _lowercase=0.1 , _lowercase="mean" , _lowercase=False , _lowercase=False , _lowercase=256 , _lowercase=80 , _lowercase=0 , _lowercase=1 , _lowercase=2 , _lowercase=0.5 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase ) __a : Union[str, Any] = hidden_size __a : Any = feat_extract_norm __a : Union[str, Any] = feat_extract_activation __a : Tuple = list(_lowercase ) __a : Dict = list(_lowercase ) __a : List[Any] = list(_lowercase ) __a : List[Any] = conv_bias __a : Optional[Any] = num_conv_pos_embeddings __a : Union[str, Any] = num_conv_pos_embedding_groups __a : Dict = len(self.conv_dim ) __a : Dict = num_hidden_layers __a : Union[str, Any] = intermediate_size __a : List[str] = hidden_act __a : int = num_attention_heads __a : int = hidden_dropout __a : Any = attention_dropout __a : List[Any] = activation_dropout __a : List[Any] = feat_proj_dropout __a : Union[str, Any] = final_dropout __a : str = layerdrop __a : Dict = layer_norm_eps __a : Dict = initializer_range __a : Union[str, Any] = num_ctc_classes __a : List[Any] = vocab_size __a : Any = do_stable_layer_norm __a : List[str] = use_weighted_layer_sum __a : List[str] = 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 __a : Dict = apply_spec_augment __a : Union[str, Any] = mask_time_prob __a : List[str] = mask_time_length __a : Dict = mask_time_min_masks __a : List[Any] = mask_feature_prob __a : Tuple = mask_feature_length __a : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __a : List[Any] = num_codevectors_per_group __a : Union[str, Any] = num_codevector_groups __a : List[Any] = contrastive_logits_temperature __a : Any = feat_quantizer_dropout __a : Optional[int] = num_negatives __a : List[str] = codevector_dim __a : List[Any] = proj_codevector_dim __a : Tuple = diversity_loss_weight # ctc loss __a : Any = ctc_loss_reduction __a : List[str] = ctc_zero_infinity # pretraining loss __a : Tuple = replace_prob @property def lowerCAmelCase__(self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
63
0
"""simple docstring""" import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def __magic_name__ ( _lowerCamelCase : Union[str, Any]=None ): if subparsers is not None: __a : Union[str, Any] = subparsers.add_parser("""env""" ) else: __a : int = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=_lowerCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=_lowerCamelCase ) return parser def __magic_name__ ( _lowerCamelCase : List[str] ): __a : List[Any] = torch.__version__ __a : Any = torch.cuda.is_available() __a : Dict = is_xpu_available() __a : Tuple = is_npu_available() __a : List[str] = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(_lowerCamelCase ): __a : Optional[Any] = load_config_from_file(args.config_file ).to_dict() __a : List[Any] = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F'''{pt_version} ({pt_cuda_available})''', """PyTorch XPU available""": str(_lowerCamelCase ), """PyTorch NPU available""": str(_lowerCamelCase ), """System RAM""": F'''{psutil.virtual_memory().total / 1_0_2_4 ** 3:.2f} GB''', } if pt_cuda_available: __a : List[str] = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F'''- {prop}: {val}''' for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) __a : List[str] = ( """\n""".join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else F'''\t{accelerate_config}''' ) print(_lowerCamelCase ) __a : str = accelerate_config return info def __magic_name__ ( ): __a : Optional[Any] = env_command_parser() __a : Optional[Any] = parser.parse_args() env_command(_lowerCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
710
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase = 13 , _lowercase = 64 , _lowercase = 2 , _lowercase = 3 , _lowercase = 3 , _lowercase = True , _lowercase = True , _lowercase = 128 , _lowercase=[16, 32, 64, 128] , _lowercase = 7 , _lowercase = 4 , _lowercase = 37 , _lowercase = "gelu" , _lowercase = 0.1 , _lowercase = 0.1 , _lowercase = 10 , _lowercase = 0.02 , _lowercase = 2 , _lowercase = 1 , _lowercase = 128 , _lowercase = [2, 2, 2, 2] , _lowercase = 2 , _lowercase = 2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : int = image_size __a : Tuple = patch_size __a : str = num_channels __a : Union[str, Any] = is_training __a : List[Any] = use_labels __a : int = hidden_size __a : Optional[Any] = num_hidden_layers __a : List[Any] = num_attention_heads __a : Dict = intermediate_size __a : str = hidden_act __a : Dict = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Optional[int] = type_sequence_label_size __a : Dict = initializer_range __a : Dict = encoder_stride __a : int = num_attention_outputs __a : List[Any] = embed_dim __a : Optional[Any] = embed_dim + 1 __a : Optional[Any] = resolution __a : Optional[Any] = depths __a : Union[str, Any] = hidden_sizes __a : List[str] = dim __a : Any = mlp_expansion_ratio def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : str = None if self.use_labels: __a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowercase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = TFEfficientFormerModel(config=_lowercase ) __a : List[Any] = model(_lowercase , training=_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Optional[Any] = self.type_sequence_label_size __a : Any = TFEfficientFormerForImageClassification(_lowercase ) __a : Union[str, Any] = model(_lowercase , labels=_lowercase , training=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a : Optional[Any] = 1 __a : int = TFEfficientFormerForImageClassification(_lowercase ) __a : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : str = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) _lowerCAmelCase = ( { "feature-extraction": TFEfficientFormerModel, "image-classification": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = TFEfficientFormerModelTester(self ) __a : Any = ConfigTester( self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(_lowercase ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Union[str, Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : Tuple = model_class(_lowercase ) __a : int = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a : str = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(_lowercase ) , _lowercase ) if hasattr(self.model_tester , """encoder_seq_length""" ): __a : Any = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: __a : int = seq_length * self.model_tester.chunk_length else: __a : Any = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __a : Optional[int] = outputs.decoder_hidden_states self.asseretIsInstance(_lowercase , (list, tuple) ) self.assertEqual(len(_lowercase ) , _lowercase ) __a : Any = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : List[Any] = getattr(self.model_tester , """decoder_seq_length""" , _lowercase ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : int = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' __a : Any = super()._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = TFEfficientFormerModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : int = True __a : Optional[int] = getattr(self.model_tester , """seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """encoder_seq_length""" , _lowercase ) __a : Dict = getattr(self.model_tester , """key_length""" , _lowercase ) __a : int = getattr(self.model_tester , """chunk_length""" , _lowercase ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): __a : List[str] = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __a : List[Any] = True __a : Tuple = False __a : List[Any] = True __a : int = model_class(_lowercase ) __a : List[Any] = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : Dict = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a : Optional[Any] = True __a : List[str] = model_class(_lowercase ) __a : Dict = model(**self._prepare_for_class(_lowercase , _lowercase ) , training=_lowercase ) __a : int = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_lowercase ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def lowerCAmelCase__(self ): '''simple docstring''' __a , __a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __a : Dict = model_class(_lowercase ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __a : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=_lowercase ) for key, val in model.input_signature.items() if key in model.dummy_inputs } __a : Optional[Any] = model(_lowercase ) self.assertTrue(outputs_dict is not None ) def __magic_name__ ( ): __a : int = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : str = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) __a : Optional[Any] = self.default_image_processor __a : List[str] = prepare_img() __a : int = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : Optional[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : str = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : Dict = tf.constant([-0.0555, 0.4825, -0.0852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) ) @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) __a : Any = self.default_image_processor __a : str = prepare_img() __a : str = image_processor(images=_lowercase , return_tensors="""tf""" ) # forward pass __a : List[Any] = model(**_lowercase , training=_lowercase ) # verify the logits __a : int = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : List[str] = tf.constant([-0.1312, 0.4353, -1.0499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
63
0
"""simple docstring""" import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' super().tearDown() gc.collect() def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-canny""" , from_pt=_lowercase , dtype=jnp.bfloataa ) __a : Any = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=_lowercase , from_pt=_lowercase , dtype=jnp.bfloataa ) __a : List[str] = controlnet_params __a : Any = """bird""" __a : Tuple = jax.device_count() __a : int = pipe.prepare_text_inputs([prompts] * num_samples ) __a : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ) __a : Tuple = pipe.prepare_image_inputs([canny_image] * num_samples ) __a : Union[str, Any] = jax.random.PRNGKey(0 ) __a : Optional[int] = jax.random.split(_lowercase , jax.device_count() ) __a : str = replicate(_lowercase ) __a : Optional[int] = shard(_lowercase ) __a : Optional[int] = shard(_lowercase ) __a : Tuple = pipe( prompt_ids=_lowercase , image=_lowercase , params=_lowercase , prng_seed=_lowercase , num_inference_steps=50 , jit=_lowercase , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __a : List[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __a : Union[str, Any] = images[0, 253:256, 253:256, -1] __a : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __a : Tuple = jnp.array( [0.16_7969, 0.11_6699, 0.08_1543, 0.15_4297, 0.13_2812, 0.10_8887, 0.16_9922, 0.16_9922, 0.20_5078] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-openpose""" , from_pt=_lowercase , dtype=jnp.bfloataa ) __a : str = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=_lowercase , from_pt=_lowercase , dtype=jnp.bfloataa ) __a : List[str] = controlnet_params __a : Union[str, Any] = """Chef in the kitchen""" __a : List[str] = jax.device_count() __a : Dict = pipe.prepare_text_inputs([prompts] * num_samples ) __a : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png""" ) __a : Optional[Any] = pipe.prepare_image_inputs([pose_image] * num_samples ) __a : Dict = jax.random.PRNGKey(0 ) __a : int = jax.random.split(_lowercase , jax.device_count() ) __a : int = replicate(_lowercase ) __a : Optional[int] = shard(_lowercase ) __a : str = shard(_lowercase ) __a : Optional[int] = pipe( prompt_ids=_lowercase , image=_lowercase , params=_lowercase , prng_seed=_lowercase , num_inference_steps=50 , jit=_lowercase , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) __a : str = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __a : List[str] = images[0, 253:256, 253:256, -1] __a : str = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __a : Tuple = jnp.array( [[0.27_1484, 0.26_1719, 0.27_5391, 0.27_7344, 0.27_9297, 0.29_1016, 0.29_4922, 0.30_2734, 0.30_2734]] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
711
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=0 ): '''simple docstring''' __a : Any = 1.0 if scale is None else scale __a : str = 0.0 if loc is None else loc super().__init__(_lowercase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=_lowercase )] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.variance.sqrt() class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' super().__init__(**_lowercase ) __a : str = args_dim __a : List[Any] = nn.ModuleList([nn.Linear(_lowercase , _lowercase ) for dim in args_dim.values()] ) __a : Dict = domain_map def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[Any] = [proj(_lowercase ) for proj in self.proj] return self.domain_map(*_lowercase ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__() __a : Optional[int] = function def lowerCAmelCase__(self , _lowercase , *_lowercase ): '''simple docstring''' return self.function(_lowercase , *_lowercase ) class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 42 _lowerCAmelCase = 42 _lowerCAmelCase = 42 def __init__(self , _lowercase = 1 ): '''simple docstring''' __a : Optional[int] = dim __a : str = {k: dim * self.args_dim[k] for k in self.args_dim} def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if self.dim == 1: return self.distribution_class(*_lowercase ) else: return Independent(self.distribution_class(*_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , ): '''simple docstring''' __a : Tuple = self._base_distribution(_lowercase ) if loc is None and scale is None: return distr else: return AffineTransformed(_lowercase , loc=_lowercase , scale=_lowercase , event_dim=self.event_dim ) @property def lowerCAmelCase__(self ): '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.event_shape ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 0.0 def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return ParameterProjection( in_features=_lowercase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def lowerCAmelCase__(self , *_lowercase ): '''simple docstring''' raise NotImplementedError() @staticmethod def lowerCAmelCase__(_lowercase ): '''simple docstring''' return (x + torch.sqrt(torch.square(_lowercase ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"df": 1, "loc": 1, "scale": 1} _lowerCAmelCase = StudentT @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) __a : Optional[Any] = 2.0 + cls.squareplus(_lowercase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"loc": 1, "scale": 1} _lowerCAmelCase = Normal @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : str = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"total_count": 1, "logits": 1} _lowerCAmelCase = NegativeBinomial @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = cls.squareplus(_lowercase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a , __a : Optional[Any] = distr_args if self.dim == 1: return self.distribution_class(total_count=_lowercase , logits=_lowercase ) else: return Independent(self.distribution_class(total_count=_lowercase , logits=_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None ): '''simple docstring''' __a , __a : List[Any] = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
63
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase , _lowercase=13 , _lowercase=32 , _lowercase=3 , _lowercase=4 , _lowercase=[10, 20, 30, 40] , _lowercase=[2, 2, 3, 2] , _lowercase=True , _lowercase=True , _lowercase=37 , _lowercase="gelu" , _lowercase=10 , _lowercase=0.02 , _lowercase=["stage2", "stage3", "stage4"] , _lowercase=[2, 3, 4] , _lowercase=None , ): '''simple docstring''' __a : Tuple = parent __a : Any = batch_size __a : List[Any] = image_size __a : str = num_channels __a : Any = num_stages __a : Union[str, Any] = hidden_sizes __a : Optional[int] = depths __a : Dict = is_training __a : int = use_labels __a : str = intermediate_size __a : Any = hidden_act __a : Optional[Any] = num_labels __a : Any = initializer_range __a : Dict = out_features __a : Tuple = out_indices __a : Union[str, Any] = scope def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Optional[Any] = None if self.use_labels: __a : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __a : Any = self.get_config() return config, pixel_values, labels def lowerCAmelCase__(self ): '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_lowercase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Tuple = ConvNextVaModel(config=_lowercase ) model.to(_lowercase ) model.eval() __a : Tuple = model(_lowercase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : str = ConvNextVaForImageClassification(_lowercase ) model.to(_lowercase ) model.eval() __a : Dict = model(_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = ConvNextVaBackbone(config=_lowercase ) model.to(_lowercase ) model.eval() __a : Optional[int] = model(_lowercase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __a : Tuple = None __a : Tuple = ConvNextVaBackbone(config=_lowercase ) model.to(_lowercase ) model.eval() __a : List[str] = model(_lowercase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.prepare_config_and_inputs() __a : Optional[int] = config_and_inputs __a : int = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = self.prepare_config_and_inputs() __a : List[Any] = config_and_inputs __a : str = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCAmelCase = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) _lowerCAmelCase = ( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = ConvNextVaModelTester(self ) __a : Tuple = ConfigTester(self , config_class=_lowercase , has_text_modality=_lowercase , hidden_size=37 ) def lowerCAmelCase__(self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase__(self ): '''simple docstring''' return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: __a : int = self.model_tester.prepare_config_and_inputs_with_labels() __a : List[str] = True if model_class.__name__ in [ *get_values(_lowercase ), *get_values(_lowercase ), ]: continue __a : Optional[int] = model_class(_lowercase ) model.to(_lowercase ) model.train() __a : Tuple = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) __a : Dict = model(**_lowercase ).loss loss.backward() def lowerCAmelCase__(self ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: __a : List[str] = self.model_tester.prepare_config_and_inputs_with_labels() __a : Optional[Any] = False __a : List[Any] = True if ( model_class.__name__ in [*get_values(_lowercase ), *get_values(_lowercase )] or not model_class.supports_gradient_checkpointing ): continue __a : Optional[int] = model_class(_lowercase ) model.to(_lowercase ) model.gradient_checkpointing_enable() model.train() __a : Optional[int] = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase ) __a : Any = model(**_lowercase ).loss loss.backward() def lowerCAmelCase__(self ): '''simple docstring''' __a : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = model_class(_lowercase ) __a : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : List[str] = [*signature.parameters.keys()] __a : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): __a : Any = model_class(_lowercase ) model.to(_lowercase ) model.eval() with torch.no_grad(): __a : Tuple = model(**self._prepare_for_class(_lowercase , _lowercase ) ) __a : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __a : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(_lowercase ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Tuple = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Tuple = True check_hidden_states_output(_lowercase , _lowercase , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowercase ) @slow def lowerCAmelCase__(self ): '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Union[str, Any] = ConvNextVaModel.from_pretrained(_lowercase ) self.assertIsNotNone(_lowercase ) def __magic_name__ ( ): __a : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(_lowercase ) __a : Dict = self.default_image_processor __a : Union[str, Any] = prepare_img() __a : Union[str, Any] = preprocessor(images=_lowercase , return_tensors="""pt""" ).to(_lowercase ) # forward pass with torch.no_grad(): __a : List[Any] = model(**_lowercase ) # verify the logits __a : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowercase ) __a : Any = torch.tensor([0.9996, 0.1966, -0.4386] ).to(_lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) )
712
"""simple docstring""" import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = KandinskyVaaPriorPipeline _lowerCAmelCase = ["prompt"] _lowerCAmelCase = ["prompt", "negative_prompt"] _lowerCAmelCase = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] _lowerCAmelCase = False @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return 32 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim @property def lowerCAmelCase__(self ): '''simple docstring''' return self.time_input_dim * 4 @property def lowerCAmelCase__(self ): '''simple docstring''' return 100 @property def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_lowercase ) @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : Dict = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } __a : Tuple = PriorTransformer(**_lowercase ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __a : int = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' torch.manual_seed(0 ) __a : List[str] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __a : Optional[Any] = CLIPVisionModelWithProjection(_lowercase ) return model @property def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = CLIPImageProcessor( crop_size=224 , do_center_crop=_lowercase , do_normalize=_lowercase , do_resize=_lowercase , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = self.dummy_prior __a : int = self.dummy_image_encoder __a : Any = self.dummy_text_encoder __a : int = self.dummy_tokenizer __a : Optional[Any] = self.dummy_image_processor __a : List[Any] = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=_lowercase , clip_sample_range=10.0 , ) __a : List[Any] = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def lowerCAmelCase__(self , _lowercase , _lowercase=0 ): '''simple docstring''' if str(_lowercase ).startswith("""mps""" ): __a : Dict = torch.manual_seed(_lowercase ) else: __a : Union[str, Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __a : Union[str, Any] = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = """cpu""" __a : Union[str, Any] = self.get_dummy_components() __a : Dict = self.pipeline_class(**_lowercase ) __a : Tuple = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __a : Optional[int] = pipe(**self.get_dummy_inputs(_lowercase ) ) __a : str = output.image_embeds __a : Any = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] __a : List[Any] = image[0, -10:] __a : List[Any] = image_from_tuple[0, -10:] assert image.shape == (1, 32) __a : Optional[Any] = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = torch_device == """cpu""" __a : Any = True __a : Any = False self._test_inference_batch_single_identical( test_max_difference=_lowercase , relax_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , ) @skip_mps def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = torch_device == """cpu""" __a : Union[str, Any] = False self._test_attention_slicing_forward_pass( test_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , )
63
0
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=0 ): '''simple docstring''' __a : Any = 1.0 if scale is None else scale __a : str = 0.0 if loc is None else loc super().__init__(_lowercase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=_lowercase )] ) @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def lowerCAmelCase__(self ): '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def lowerCAmelCase__(self ): '''simple docstring''' return self.variance.sqrt() class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase , _lowercase , _lowercase , **_lowercase ): '''simple docstring''' super().__init__(**_lowercase ) __a : str = args_dim __a : List[Any] = nn.ModuleList([nn.Linear(_lowercase , _lowercase ) for dim in args_dim.values()] ) __a : Dict = domain_map def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : List[Any] = [proj(_lowercase ) for proj in self.proj] return self.domain_map(*_lowercase ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__(self , _lowercase ): '''simple docstring''' super().__init__() __a : Optional[int] = function def lowerCAmelCase__(self , _lowercase , *_lowercase ): '''simple docstring''' return self.function(_lowercase , *_lowercase ) class SCREAMING_SNAKE_CASE__ : _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 _lowerCAmelCase = 4_2 def __init__(self , _lowercase = 1 ): '''simple docstring''' __a : Optional[int] = dim __a : str = {k: dim * self.args_dim[k] for k in self.args_dim} def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if self.dim == 1: return self.distribution_class(*_lowercase ) else: return Independent(self.distribution_class(*_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None , ): '''simple docstring''' __a : Tuple = self._base_distribution(_lowercase ) if loc is None and scale is None: return distr else: return AffineTransformed(_lowercase , loc=_lowercase , scale=_lowercase , event_dim=self.event_dim ) @property def lowerCAmelCase__(self ): '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def lowerCAmelCase__(self ): '''simple docstring''' return len(self.event_shape ) @property def lowerCAmelCase__(self ): '''simple docstring''' return 0.0 def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return ParameterProjection( in_features=_lowercase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def lowerCAmelCase__(self , *_lowercase ): '''simple docstring''' raise NotImplementedError() @staticmethod def lowerCAmelCase__(_lowercase ): '''simple docstring''' return (x + torch.sqrt(torch.square(_lowercase ) + 4.0 )) / 2.0 class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"df": 1, "loc": 1, "scale": 1} _lowerCAmelCase = StudentT @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : int = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) __a : Optional[Any] = 2.0 + cls.squareplus(_lowercase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"loc": 1, "scale": 1} _lowerCAmelCase = Normal @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : str = cls.squareplus(_lowercase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = {"total_count": 1, "logits": 1} _lowerCAmelCase = NegativeBinomial @classmethod def lowerCAmelCase__(cls , _lowercase , _lowercase ): '''simple docstring''' __a : Union[str, Any] = cls.squareplus(_lowercase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : Optional[Any] = distr_args if self.dim == 1: return self.distribution_class(total_count=_lowercase , logits=_lowercase ) else: return Independent(self.distribution_class(total_count=_lowercase , logits=_lowercase ) , 1 ) def lowerCAmelCase__(self , _lowercase , _lowercase = None , _lowercase = None ): '''simple docstring''' __a : List[Any] = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
713
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ): _lowerCAmelCase = LEDTokenizer _lowerCAmelCase = LEDTokenizerFast _lowerCAmelCase = True def lowerCAmelCase__(self ): '''simple docstring''' super().setUp() __a : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __a : int = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) __a : Optional[int] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __a : List[Any] = {"""unk_token""": """<unk>"""} __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_lowercase ) ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , **_lowercase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **_lowercase ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return "lower newer", "lower newer" @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def lowerCAmelCase__(self ): '''simple docstring''' return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] __a : List[str] = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer(_lowercase , max_length=len(_lowercase ) , padding=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __a : Dict = batch.input_ids.tolist()[0] self.assertListEqual(_lowercase , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Union[str, Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Tuple = tokenizer(_lowercase , padding=_lowercase , return_tensors="""pt""" ) self.assertIn("""input_ids""" , _lowercase ) self.assertIn("""attention_mask""" , _lowercase ) self.assertNotIn("""labels""" , _lowercase ) self.assertNotIn("""decoder_attention_mask""" , _lowercase ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[Any] = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Dict = tokenizer(text_target=_lowercase , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[int] = tokenizer( ["""I am a small frog""" * 1024, """I am a small frog"""] , padding=_lowercase , truncation=_lowercase , return_tensors="""pt""" ) self.assertIsInstance(_lowercase , _lowercase ) self.assertEqual(batch.input_ids.shape , (2, 5122) ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = ["""A long paragraph for summarization."""] __a : Dict = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : int = tokenizer(_lowercase , return_tensors="""pt""" ) __a : Dict = tokenizer(text_target=_lowercase , return_tensors="""pt""" ) __a : List[str] = inputs["""input_ids"""] __a : List[Any] = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a : Optional[Any] = ["""Summary of the text.""", """Another summary."""] __a : List[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a : Union[str, Any] = tokenizer(_lowercase , padding=_lowercase ) __a : Tuple = [[0] * len(_lowercase ) for x in encoded_output["""input_ids"""]] __a : Union[str, Any] = tokenizer.pad(_lowercase ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , _lowercase ) def lowerCAmelCase__(self ): '''simple docstring''' pass def lowerCAmelCase__(self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __a : Dict = self.rust_tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = self.tokenizer_class.from_pretrained(_lowercase , **_lowercase ) __a : Union[str, Any] = """A, <mask> AllenNLP sentence.""" __a : Dict = tokenizer_r.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) __a : Tuple = tokenizer_p.encode_plus(_lowercase , add_special_tokens=_lowercase , return_token_type_ids=_lowercase ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) __a : Tuple = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) __a : Any = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( _lowercase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
63
0
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 4_2 @flax_register_to_config class SCREAMING_SNAKE_CASE__ ( nn.Module , __snake_case , __snake_case ): _lowerCAmelCase = 3_2 _lowerCAmelCase = 4 _lowerCAmelCase = 4 _lowerCAmelCase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _lowerCAmelCase = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") _lowerCAmelCase = False _lowerCAmelCase = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) _lowerCAmelCase = 2 _lowerCAmelCase = 8 _lowerCAmelCase = None _lowerCAmelCase = 1_2_8_0 _lowerCAmelCase = 0.0 _lowerCAmelCase = False _lowerCAmelCase = jnp.floataa _lowerCAmelCase = True _lowerCAmelCase = 0 _lowerCAmelCase = False def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : Dict = (1, self.in_channels, self.sample_size, self.sample_size) __a : Optional[int] = jnp.zeros(_lowercase , dtype=jnp.floataa ) __a : List[str] = jnp.ones((1,) , dtype=jnp.intaa ) __a : str = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) __a : List[str] = jax.random.split(_lowercase ) __a : Tuple = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_lowercase , _lowercase , _lowercase , _lowercase )["params"] def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = self.block_out_channels __a : List[Any] = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __a : Union[str, Any] = self.num_attention_heads or self.attention_head_dim # input __a : List[Any] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __a : Optional[Any] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) __a : Optional[Any] = FlaxTimestepEmbedding(_lowercase , dtype=self.dtype ) __a : str = self.only_cross_attention if isinstance(_lowercase , _lowercase ): __a : Dict = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_lowercase , _lowercase ): __a : int = (num_attention_heads,) * len(self.down_block_types ) # down __a : Union[str, Any] = [] __a : Optional[Any] = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): __a : List[Any] = output_channel __a : Dict = block_out_channels[i] __a : Dict = i == len(_lowercase ) - 1 if down_block_type == "CrossAttnDownBlock2D": __a : Optional[Any] = FlaxCrossAttnDownBlockaD( in_channels=_lowercase , out_channels=_lowercase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: __a : Optional[Any] = FlaxDownBlockaD( in_channels=_lowercase , out_channels=_lowercase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_lowercase ) __a : Optional[int] = down_blocks # mid __a : Tuple = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up __a : Optional[int] = [] __a : Union[str, Any] = list(reversed(_lowercase ) ) __a : List[str] = list(reversed(_lowercase ) ) __a : Tuple = list(reversed(_lowercase ) ) __a : Dict = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): __a : Union[str, Any] = output_channel __a : Tuple = reversed_block_out_channels[i] __a : Optional[int] = reversed_block_out_channels[min(i + 1 , len(_lowercase ) - 1 )] __a : List[str] = i == len(_lowercase ) - 1 if up_block_type == "CrossAttnUpBlock2D": __a : List[Any] = FlaxCrossAttnUpBlockaD( in_channels=_lowercase , out_channels=_lowercase , prev_output_channel=_lowercase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: __a : Any = FlaxUpBlockaD( in_channels=_lowercase , out_channels=_lowercase , prev_output_channel=_lowercase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(_lowercase ) __a : Union[str, Any] = output_channel __a : int = up_blocks # out __a : Optional[Any] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) __a : Optional[Any] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__(self , _lowercase , _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase = True , _lowercase = False , ): '''simple docstring''' if not isinstance(_lowercase , jnp.ndarray ): __a : Union[str, Any] = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_lowercase , jnp.ndarray ) and len(timesteps.shape ) == 0: __a : Union[str, Any] = timesteps.astype(dtype=jnp.floataa ) __a : List[str] = jnp.expand_dims(_lowercase , 0 ) __a : Any = self.time_proj(_lowercase ) __a : Tuple = self.time_embedding(_lowercase ) # 2. pre-process __a : Optional[Any] = jnp.transpose(_lowercase , (0, 2, 3, 1) ) __a : List[str] = self.conv_in(_lowercase ) # 3. down __a : Dict = (sample,) for down_block in self.down_blocks: if isinstance(_lowercase , _lowercase ): __a : Tuple = down_block(_lowercase , _lowercase , _lowercase , deterministic=not train ) else: __a : Tuple = down_block(_lowercase , _lowercase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: __a : Dict = () for down_block_res_sample, down_block_additional_residual in zip( _lowercase , _lowercase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) __a : Dict = new_down_block_res_samples # 4. mid __a : Dict = self.mid_block(_lowercase , _lowercase , _lowercase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: __a : List[str] = down_block_res_samples[-(self.layers_per_block + 1) :] __a : Optional[Any] = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(_lowercase , _lowercase ): __a : List[str] = up_block( _lowercase , temb=_lowercase , encoder_hidden_states=_lowercase , res_hidden_states_tuple=_lowercase , deterministic=not train , ) else: __a : Tuple = up_block(_lowercase , temb=_lowercase , res_hidden_states_tuple=_lowercase , deterministic=not train ) # 6. post-process __a : Optional[Any] = self.conv_norm_out(_lowercase ) __a : Optional[Any] = nn.silu(_lowercase ) __a : Any = self.conv_out(_lowercase ) __a : int = jnp.transpose(_lowercase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=_lowercase )
714
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=512, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def __magic_name__ ( _lowerCamelCase : Optional[Any] ): if string == "True": return True elif string == "False": return False else: raise ValueError(F'''could not parse string as bool {string}''' ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) lowercase__ = parser.parse_args() lowercase__ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
63
0
"""simple docstring""" import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case ): _lowerCAmelCase = 1 @register_to_config def __init__(self , _lowercase = 1000 , _lowercase = None ): '''simple docstring''' self.set_timesteps(_lowercase ) # standard deviation of the initial noise distribution __a : Union[str, Any] = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. __a : Union[str, Any] = 4 # running values __a : int = [] def lowerCAmelCase__(self , _lowercase , _lowercase = None ): '''simple docstring''' __a : Dict = num_inference_steps __a : List[str] = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] __a : Dict = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: __a : Any = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: __a : Optional[Any] = torch.sin(steps * math.pi / 2 ) ** 2 __a : Any = (1.0 - self.betas**2) ** 0.5 __a : Optional[int] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] __a : List[str] = timesteps.to(_lowercase ) __a : Union[str, Any] = [] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) __a : Dict = (self.timesteps == timestep).nonzero().item() __a : Union[str, Any] = timestep_index + 1 __a : Any = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(_lowercase ) if len(self.ets ) == 1: __a : Dict = self.ets[-1] elif len(self.ets ) == 2: __a : Any = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: __a : Optional[int] = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: __a : int = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) __a : Dict = self._get_prev_sample(_lowercase , _lowercase , _lowercase , _lowercase ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowercase ) def lowerCAmelCase__(self , _lowercase , *_lowercase , **_lowercase ): '''simple docstring''' return sample def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Any = self.alphas[timestep_index] __a : Dict = self.betas[timestep_index] __a : Any = self.alphas[prev_timestep_index] __a : Any = self.betas[prev_timestep_index] __a : Dict = (sample - sigma * ets) / max(_lowercase , 1e-8 ) __a : List[str] = next_alpha * pred + ets * next_sigma return prev_sample def __len__(self ): '''simple docstring''' return self.config.num_train_timesteps
715
"""simple docstring""" import torch from diffusers import DiffusionPipeline class SCREAMING_SNAKE_CASE__ ( __snake_case ): def __init__(self , _lowercase , _lowercase ): '''simple docstring''' super().__init__() self.register_modules(unet=_lowercase , scheduler=_lowercase ) def __call__(self ): '''simple docstring''' __a : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __a : Optional[Any] = 1 __a : List[str] = self.unet(_lowercase , _lowercase ).sample __a : Union[str, Any] = self.scheduler.step(_lowercase , _lowercase , _lowercase ).prev_sample __a : Optional[int] = scheduler_output - scheduler_output + torch.ones_like(_lowercase ) return result
63
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "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 SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "unispeech" def __init__(self , _lowercase=32 , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=1e-5 , _lowercase="group" , _lowercase="gelu" , _lowercase=(512, 512, 512, 512, 512, 512, 512) , _lowercase=(5, 2, 2, 2, 2, 2, 2) , _lowercase=(10, 3, 3, 3, 3, 2, 2) , _lowercase=False , _lowercase=128 , _lowercase=16 , _lowercase=False , _lowercase=True , _lowercase=0.05 , _lowercase=10 , _lowercase=2 , _lowercase=0.0 , _lowercase=10 , _lowercase=0 , _lowercase=320 , _lowercase=2 , _lowercase=0.1 , _lowercase=100 , _lowercase=256 , _lowercase=256 , _lowercase=0.1 , _lowercase="mean" , _lowercase=False , _lowercase=False , _lowercase=256 , _lowercase=80 , _lowercase=0 , _lowercase=1 , _lowercase=2 , _lowercase=0.5 , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase ) __a : Union[str, Any] = hidden_size __a : Any = feat_extract_norm __a : Union[str, Any] = feat_extract_activation __a : Tuple = list(_lowercase ) __a : Dict = list(_lowercase ) __a : List[Any] = list(_lowercase ) __a : List[Any] = conv_bias __a : Optional[Any] = num_conv_pos_embeddings __a : Union[str, Any] = num_conv_pos_embedding_groups __a : Dict = len(self.conv_dim ) __a : Dict = num_hidden_layers __a : Union[str, Any] = intermediate_size __a : List[str] = hidden_act __a : int = num_attention_heads __a : int = hidden_dropout __a : Any = attention_dropout __a : List[Any] = activation_dropout __a : List[Any] = feat_proj_dropout __a : Union[str, Any] = final_dropout __a : str = layerdrop __a : Dict = layer_norm_eps __a : Dict = initializer_range __a : Union[str, Any] = num_ctc_classes __a : List[Any] = vocab_size __a : Any = do_stable_layer_norm __a : List[str] = use_weighted_layer_sum __a : List[str] = 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 __a : Dict = apply_spec_augment __a : Union[str, Any] = mask_time_prob __a : List[str] = mask_time_length __a : Dict = mask_time_min_masks __a : List[Any] = mask_feature_prob __a : Tuple = mask_feature_length __a : int = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __a : List[Any] = num_codevectors_per_group __a : Union[str, Any] = num_codevector_groups __a : List[Any] = contrastive_logits_temperature __a : Any = feat_quantizer_dropout __a : Optional[int] = num_negatives __a : List[str] = codevector_dim __a : List[Any] = proj_codevector_dim __a : Tuple = diversity_loss_weight # ctc loss __a : Any = ctc_loss_reduction __a : List[str] = ctc_zero_infinity # pretraining loss __a : Tuple = replace_prob @property def lowerCAmelCase__(self ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
716
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json", # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "vit_msn" def __init__(self , _lowercase=768 , _lowercase=12 , _lowercase=12 , _lowercase=3072 , _lowercase="gelu" , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1e-06 , _lowercase=224 , _lowercase=16 , _lowercase=3 , _lowercase=True , **_lowercase , ): '''simple docstring''' super().__init__(**_lowercase ) __a : int = hidden_size __a : str = num_hidden_layers __a : str = num_attention_heads __a : Optional[Any] = intermediate_size __a : Union[str, Any] = hidden_act __a : Tuple = hidden_dropout_prob __a : Any = attention_probs_dropout_prob __a : List[Any] = initializer_range __a : Any = layer_norm_eps __a : Dict = image_size __a : List[Any] = patch_size __a : Dict = num_channels __a : Optional[Any] = qkv_bias
63
0
"""simple docstring""" class SCREAMING_SNAKE_CASE__ : def __init__(self , _lowercase ): '''simple docstring''' __a : Optional[Any] = val __a : Any = None __a : Optional[Any] = None def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: __a : Any = Node(_lowercase ) else: self.left.insert(_lowercase ) elif val > self.val: if self.right is None: __a : str = Node(_lowercase ) else: self.right.insert(_lowercase ) else: __a : Tuple = val def __magic_name__ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Any] ): # Recursive traversal if root: inorder(root.left , _lowerCamelCase ) res.append(root.val ) inorder(root.right , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optional[int] ): # Build BST if len(_lowerCamelCase ) == 0: return arr __a : Optional[int] = Node(arr[0] ) for i in range(1 , len(_lowerCamelCase ) ): root.insert(arr[i] ) # Traverse BST in order. __a : Tuple = [] inorder(_lowerCamelCase , _lowerCamelCase ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
717
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowercase__ = logging.get_logger(__name__) lowercase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } lowercase__ = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } lowercase__ = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } lowercase__ = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRContextEncoderTokenizer class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = DPRQuestionEncoderTokenizer lowercase__ = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) lowercase__ = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) lowercase__ = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ : def __call__(self , _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , **_lowercase , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) elif titles is None or texts is None: __a : str = titles if texts is None else texts return super().__call__( _lowercase , _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) __a : str = titles if not isinstance(_lowercase , _lowercase ) else [titles] __a : Optional[Any] = texts if not isinstance(_lowercase , _lowercase ) else [texts] __a : Tuple = len(_lowercase ) __a : Dict = questions if not isinstance(_lowercase , _lowercase ) else [questions] * n_passages assert len(_lowercase ) == len( _lowercase ), F'''There should be as many titles than texts but got {len(_lowercase )} titles and {len(_lowercase )} texts.''' __a : Optional[Any] = super().__call__(_lowercase , _lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : str = super().__call__(_lowercase , add_special_tokens=_lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] __a : Union[str, Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowercase , _lowercase ) ] } if return_attention_mask is not False: __a : Optional[int] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __a : str = attention_mask return self.pad(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 16 , _lowercase = 64 , _lowercase = 4 , ): '''simple docstring''' __a : Union[str, Any] = reader_input["""input_ids"""] __a , __a , __a : Optional[int] = reader_output[:3] __a : int = len(_lowercase ) __a : Any = sorted(range(_lowercase ) , reverse=_lowercase , key=relevance_logits.__getitem__ ) __a : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __a : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __a : Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __a : int = sequence_ids.index(self.pad_token_id ) else: __a : Optional[Any] = len(_lowercase ) __a : List[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowercase , top_spans=_lowercase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowercase , start_index=_lowercase , end_index=_lowercase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowercase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , ): '''simple docstring''' __a : Tuple = [] for start_index, start_score in enumerate(_lowercase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __a : str = sorted(_lowercase , key=lambda _lowercase : x[1] , reverse=_lowercase ) __a : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' __a : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowercase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__snake_case ) class SCREAMING_SNAKE_CASE__ ( __snake_case , __snake_case ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase = ["input_ids", "attention_mask"] _lowerCAmelCase = DPRReaderTokenizer
63
0
"""simple docstring""" from __future__ import annotations def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : int ): if partitions <= 0: raise ValueError("""partitions must be a positive number!""" ) if partitions > number_of_bytes: raise ValueError("""partitions can not > number_of_bytes!""" ) __a : str = number_of_bytes // partitions __a : Optional[int] = [] for i in range(_lowerCamelCase ): __a : int = i * bytes_per_partition + 1 __a : Union[str, Any] = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(F'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
718
"""simple docstring""" import os def __magic_name__ ( _lowerCamelCase : Dict ): __a : List[str] = len(grid[0] ) __a : int = len(_lowerCamelCase ) __a : Tuple = 0 __a : List[Any] = 0 __a : List[str] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_lowerCamelCase ): for j in range(n_rows - 3 ): __a : List[Any] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] __a : Tuple = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: __a : List[Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: __a : List[Any] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) __a : str = max( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if max_product > largest: __a : Optional[Any] = max_product return largest def __magic_name__ ( ): __a : Tuple = [] with open(os.path.dirname(_lowerCamelCase ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) __a : Tuple = [[int(_lowerCamelCase ) for i in grid[j]] for j in range(len(_lowerCamelCase ) )] return largest_product(_lowerCamelCase ) if __name__ == "__main__": print(solution())
63
0
"""simple docstring""" from __future__ import annotations import requests lowercase__ = set( "approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports".split() ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : int = 1 , _lowerCamelCase : str = "new" , _lowerCamelCase : list | None = None ): __a : Union[str, Any] = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(_lowerCamelCase ) - valid_terms ) ): __a : int = F'''Invalid search term: {invalid_search_terms}''' raise ValueError(_lowerCamelCase ) __a : Optional[int] = requests.get( F'''https://reddit.com/r/{subreddit}/{age}.json?limit={limit}''' , headers={"""User-agent""": """A random string"""} , ) if response.status_code == 4_2_9: raise requests.HTTPError __a : Union[str, Any] = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(_lowerCamelCase )} __a : Union[str, Any] = {} for id_ in range(_lowerCamelCase ): __a : Optional[Any] = { item: data["""data"""]["""children"""][id_]["""data"""][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
719
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = 42 _lowerCAmelCase = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
63
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ = { "configuration_xmod": [ "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP", "XmodConfig", "XmodOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "XMOD_PRETRAINED_MODEL_ARCHIVE_LIST", "XmodForCausalLM", "XmodForMaskedLM", "XmodForMultipleChoice", "XmodForQuestionAnswering", "XmodForSequenceClassification", "XmodForTokenClassification", "XmodModel", "XmodPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
720
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _lowerCAmelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCAmelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowerCAmelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowerCAmelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Optional[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __a : int = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : List[str] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __a : Optional[int] = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Tuple = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __a : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : Union[str, Any] = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __a : Optional[int] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __a : List[str] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = pipeline("""text-classification""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : Union[str, Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = pipeline("""text-classification""" , framework="""tf""" ) __a : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Tuple = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = TextClassificationPipeline(model=_lowercase , tokenizer=_lowercase ) return text_classifier, ["HuggingFace is in", "This is another test"] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __a : Union[str, Any] = """HuggingFace is in""" __a : List[str] = text_classifier(_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __a : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __a : Dict = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}, {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __a : Dict = text_classifier(_lowercase , top_k=_lowercase ) __a : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N, [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N] , ) __a : Dict = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __a : Any = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __a : Dict = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(_lowercase ): text_classifier(_lowercase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __a : Optional[int] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
63
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase__ = { "configuration_m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config", "M2M100OnnxConfig"], "tokenization_m2m_100": ["M2M100Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST", "M2M100ForConditionalGeneration", "M2M100Model", "M2M100PreTrainedModel", ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
721
"""simple docstring""" import unittest from knapsack import knapsack as k class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self ): '''simple docstring''' __a : str = 0 __a : Optional[Any] = [0] __a : int = [0] __a : str = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) __a : int = [60] __a : Union[str, Any] = [10] __a : Tuple = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : int = 3 __a : str = [1, 2, 3] __a : Optional[Any] = [3, 2, 1] __a : int = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Dict = 50 __a : Tuple = [60, 100, 120] __a : List[str] = [10, 20, 30] __a : Union[str, Any] = len(_lowercase ) self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 ) if __name__ == "__main__": unittest.main()
63
0
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math.sqrt(_lowerCamelCase ) __a : Any = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): __a : Any = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float ): # Creates a gaussian kernel of given dimension. __a : int = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowerCamelCase ): for j in range(0 , _lowerCamelCase ): __a : Any = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int , ): __a : Tuple = np.zeros(img.shape ) __a : Optional[int] = get_gauss_kernel(_lowerCamelCase , _lowerCamelCase ) __a : int = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): __a : List[str] = get_slice(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Any = img_s - img_s[kernel_size // 2, kernel_size // 2] __a : Optional[Any] = vec_gaussian(_lowerCamelCase , _lowerCamelCase ) __a : Optional[Any] = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Any = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Tuple = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) __a : Optional[Any] = val return imga def __magic_name__ ( _lowerCamelCase : list ): __a : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" __a : Union[str, Any] = float(args[2] ) if args[2:] else 1.0 __a : Optional[int] = float(args[3] ) if args[3:] else 1.0 if args[4:]: __a : Any = int(args[4] ) __a : Any = kernel_size + abs(kernel_size % 2 - 1 ) else: __a : Optional[int] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": lowercase__ , lowercase__ , lowercase__ , lowercase__ = parse_args(sys.argv) lowercase__ = cva.imread(filename, 0) cva.imshow("input image", img) lowercase__ = img / 255 lowercase__ = out.astype("float32") lowercase__ = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) lowercase__ = out * 255 lowercase__ = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
700
"""simple docstring""" from manim import * class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = Rectangle(height=0.5 , width=0.5 ) __a : Union[str, Any] = Rectangle(height=0.25 , width=0.25 ) __a : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a : Dict = [mem.copy() for i in range(6 )] __a : str = [mem.copy() for i in range(6 )] __a : Tuple = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[Any] = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Union[str, Any] = Text("""CPU""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(4 )] __a : Dict = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = Text("""GPU""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) gpu.move_to([-1, -1, 0] ) self.add(_lowercase ) __a : List[Any] = [mem.copy() for i in range(6 )] __a : Any = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Optional[Any] = Text("""Model""" , font_size=24 ) __a : Any = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) model.move_to([3, -1.0, 0] ) self.add(_lowercase ) __a : Tuple = [] __a : Tuple = [] __a : Optional[int] = [] for i, rect in enumerate(_lowercase ): rect.set_stroke(_lowercase ) __a : str = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_lowercase , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowercase ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=_lowercase , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=_lowercase , buff=0.0 ) self.add(_lowercase ) model_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase , *_lowercase ) __a : Optional[Any] = [mem.copy() for i in range(6 )] __a : Union[str, Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Any = Text("""Loaded Checkpoint""" , font_size=24 ) __a : str = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) checkpoint.move_to([3, 0.5, 0] ) self.add(_lowercase ) __a : Dict = [] __a : int = [] for i, rect in enumerate(_lowercase ): __a : List[str] = fill.copy().set_fill(_lowercase , opacity=0.7 ) target.move_to(_lowercase ) ckpt_arr.append(_lowercase ) __a : Union[str, Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(_lowercase ) self.add(*_lowercase , *_lowercase ) __a : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a : List[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_lowercase , _lowercase ) __a : str = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(_lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_lowercase ) __a : Optional[int] = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) __a : List[Any] = [meta_mem.copy() for i in range(6 )] __a : Optional[int] = [meta_mem.copy() for i in range(6 )] __a : List[Any] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : List[str] = VGroup(*_lowercase ).arrange(_lowercase , buff=0 ) __a : Tuple = VGroup(_lowercase , _lowercase ).arrange(_lowercase , buff=0 ) __a : Dict = Text("""Disk""" , font_size=24 ) __a : Dict = Group(_lowercase , _lowercase ).arrange(_lowercase , buff=0.5 , aligned_edge=_lowercase ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(_lowercase , run_time=3 ) , Write(_lowercase , run_time=1 ) , Create(_lowercase , run_time=1 ) ) __a : Optional[Any] = [] for i, rect in enumerate(_lowercase ): __a : List[str] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(_lowercase , run_time=1.5 ) ) self.play(*_lowercase ) self.play(FadeOut(_lowercase ) ) __a : List[str] = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_lowercase , run_time=3 ) ) self.play( FadeOut(_lowercase , _lowercase , *_lowercase , *_lowercase ) , ) self.wait()
63
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : list[float] ): if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError("""Cash flows list cannot be empty""" ) __a : Tuple = 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()
701
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float(moles / volume ) * nfactor ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (volume) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((moles * 0.08_21 * temperature) / (pressure) ) ) def __magic_name__ ( _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : float ): return round(float((pressure * volume) / (0.08_21 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowercase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _lowerCAmelCase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCAmelCase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: _lowerCAmelCase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: _lowerCAmelCase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : int = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Optional[Any] = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) __a : int = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : List[str] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior __a : Optional[int] = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) __a : Tuple = text_classifier("""This is great !""" , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) __a : Any = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) __a : Union[str, Any] = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def lowerCAmelCase__(self ): '''simple docstring''' import torch __a : Any = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) __a : Optional[int] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) __a : List[str] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = pipeline("""text-classification""" ) __a : Tuple = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Optional[int] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : Union[str, Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def lowerCAmelCase__(self ): '''simple docstring''' __a : List[str] = pipeline("""text-classification""" , framework="""tf""" ) __a : str = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) __a : Tuple = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) __a : str = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ): '''simple docstring''' __a : Dict = TextClassificationPipeline(model=_lowercase , tokenizer=_lowercase ) return text_classifier, ["HuggingFace is in", "This is another test"] def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __a : Union[str, Any] = """HuggingFace is in""" __a : List[str] = text_classifier(_lowercase ) self.assertEqual(nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) __a : Optional[int] = ["""HuggingFace is in """, """Paris is in France"""] __a : Dict = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}, {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __a : Dict = text_classifier(_lowercase , top_k=_lowercase ) __a : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(_lowercase ) , [[{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N, [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] * N] , ) __a : Dict = {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""} __a : Any = text_classifier(_lowercase ) self.assertEqual( nested_simplify(_lowercase ) , {"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __a : Dict = [["""HuggingFace is in """, """Paris is in France"""]] with self.assertRaises(_lowercase ): text_classifier(_lowercase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __a : Optional[int] = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(_lowercase ) , [{"""label""": ANY(_lowercase ), """score""": ANY(_lowercase )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
702
"""simple docstring""" def __magic_name__ ( _lowerCamelCase : list[int] ): if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) __a : Any = sum(_lowerCamelCase ) / len(_lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
63
0
"""simple docstring""" import sys from pathlib import Path lowercase__ = Path(__file__).resolve().parents[3] / "src" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) lowercase__ = {"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"} lowercase__ = "zero2" lowercase__ = "zero3" lowercase__ = [ZEROa, ZEROa] def __magic_name__ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : Tuple ): # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param __a : str = parameterized.to_safe_name("""_""".join(str(_lowerCamelCase ) for x in param.args ) ) return F'''{func.__name__}_{param_based_name}''' # Cartesian-product of zero stages with models to test lowercase__ = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( __snake_case ): @parameterized.expand(_lowercase , name_func=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' self.run_and_check( stage=_lowercase , model=_lowercase , distributed=_lowercase , fpaa=_lowercase , ) @require_torch_multi_gpu @parameterized.expand(_lowercase , name_func=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' self.run_and_check( stage=_lowercase , model=_lowercase , distributed=_lowercase , fpaa=_lowercase , ) @parameterized.expand(_lowercase , name_func=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' self.run_and_check( stage=_lowercase , model=_lowercase , distributed=_lowercase , fpaa=_lowercase , ) @require_torch_multi_gpu @parameterized.expand(_lowercase , name_func=_lowercase ) def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' self.run_and_check( stage=_lowercase , model=_lowercase , distributed=_lowercase , fpaa=_lowercase , ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' pass def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 10 , _lowercase = True , _lowercase = True , _lowercase = True , ): '''simple docstring''' __a : Dict = models[model] __a : List[str] = self.run_trainer( stage=_lowercase , model_name=_lowercase , eval_steps=_lowercase , num_train_epochs=1 , distributed=_lowercase , fpaa=_lowercase , ) self.do_checks(_lowercase ) return output_dir def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase = 10 , _lowercase = 1 , _lowercase = True , _lowercase = True , ): '''simple docstring''' __a : int = self.get_auto_remove_tmp_dir("""./xxx""" , after=_lowercase ) __a : List[Any] = F''' --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(_lowercase )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none '''.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files __a : List[Any] = F'''--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'''.split() __a : Any = [F'''{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py'''] __a : Dict = self.get_launcher(_lowercase ) __a : Tuple = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(_lowercase , env=self.get_env() ) return output_dir def lowerCAmelCase__(self , _lowercase=False ): '''simple docstring''' __a : Tuple = min(2 , get_gpu_count() ) if distributed else 1 return F'''deepspeed --num_nodes 1 --num_gpus {num_gpus}'''.split()
703
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math.sqrt(_lowerCamelCase ) __a : Any = 1 / (sigma * math.sqrt(2 * math.pi )) return cons * np.exp(-((img / sigma) ** 2) * 0.5 ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int ): __a : Any = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : float ): # Creates a gaussian kernel of given dimension. __a : int = np.zeros((kernel_size, kernel_size) ) for i in range(0 , _lowerCamelCase ): for j in range(0 , _lowerCamelCase ): __a : Any = math.sqrt( abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 ) return vec_gaussian(_lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : int , ): __a : Tuple = np.zeros(img.shape ) __a : Optional[int] = get_gauss_kernel(_lowerCamelCase , _lowerCamelCase ) __a , __a : int = img.shape for i in range(kernel_size // 2 , size_x - kernel_size // 2 ): for j in range(kernel_size // 2 , size_y - kernel_size // 2 ): __a : List[str] = get_slice(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __a : Any = img_s - img_s[kernel_size // 2, kernel_size // 2] __a : Optional[Any] = vec_gaussian(_lowerCamelCase , _lowerCamelCase ) __a : Optional[Any] = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Any = np.multiply(_lowerCamelCase , _lowerCamelCase ) __a : Tuple = np.sum(_lowerCamelCase ) / np.sum(_lowerCamelCase ) __a : Optional[Any] = val return imga def __magic_name__ ( _lowerCamelCase : list ): __a : Optional[Any] = args[1] if args[1:] else """../image_data/lena.jpg""" __a : Union[str, Any] = float(args[2] ) if args[2:] else 1.0 __a : Optional[int] = float(args[3] ) if args[3:] else 1.0 if args[4:]: __a : Any = int(args[4] ) __a : Any = kernel_size + abs(kernel_size % 2 - 1 ) else: __a : Optional[int] = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": lowercase__ , lowercase__ , lowercase__ , lowercase__ = parse_args(sys.argv) lowercase__ = cva.imread(filename, 0) cva.imshow("input image", img) lowercase__ = img / 255 lowercase__ = out.astype("float32") lowercase__ = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) lowercase__ = out * 255 lowercase__ = np.uinta(out) cva.imshow("output image", out) cva.waitKey(0) cva.destroyAllWindows()
63
0
"""simple docstring""" import re from filelock import FileLock try: import nltk lowercase__ = True except (ImportError, ModuleNotFoundError): lowercase__ = False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __magic_name__ ( _lowerCamelCase : str ): re.sub("""<n>""" , """""" , _lowerCamelCase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_lowerCamelCase ) )
704
"""simple docstring""" from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __magic_name__ ( ): __a : Dict = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 2_0, """a """ * 3_0, """b """ * 7], } __a : Optional[Any] = Dataset.from_dict(_lowerCamelCase ) return dataset class SCREAMING_SNAKE_CASE__ ( __snake_case ): def lowerCAmelCase__(self ): '''simple docstring''' __a : Optional[int] = get_dataset() __a : List[Any] = make_duplicate_clusters(_lowercase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def lowerCAmelCase__(self ): '''simple docstring''' __a : Tuple = get_dataset() __a , __a : Optional[Any] = deduplicate_dataset(_lowercase ) self.assertEqual(len(_lowercase ) , 2 ) print(_lowercase ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , _lowercase )
63
0
"""simple docstring""" import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowercase__ = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: lowercase__ = json.load(f) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' return FSMTTokenizer.from_pretrained(_lowercase ) def lowerCAmelCase__(self , _lowercase ): '''simple docstring''' __a : int = FSMTForConditionalGeneration.from_pretrained(_lowercase ).to(_lowercase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["""en-ru""", 26.0], ["""ru-en""", 22.0], ["""en-de""", 22.0], ["""de-en""", 29.0], ] ) @slow def lowerCAmelCase__(self , _lowercase , _lowercase ): '''simple docstring''' __a : List[Any] = F'''facebook/wmt19-{pair}''' __a : Optional[Any] = self.get_tokenizer(_lowercase ) __a : int = self.get_model(_lowercase ) __a : Optional[int] = bleu_data[pair]["""src"""] __a : Optional[Any] = bleu_data[pair]["""tgt"""] __a : Dict = tokenizer(_lowercase , return_tensors="""pt""" , truncation=_lowercase , padding="""longest""" ).to(_lowercase ) __a : List[str] = model.generate( input_ids=batch.input_ids , num_beams=8 , ) __a : Optional[Any] = tokenizer.batch_decode( _lowercase , skip_special_tokens=_lowercase , clean_up_tokenization_spaces=_lowercase ) __a : Optional[int] = calculate_bleu(_lowercase , _lowercase ) print(_lowercase ) self.assertGreaterEqual(scores["""bleu"""] , _lowercase )
705
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available lowercase__ = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
63
0
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase__ = { "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } def __magic_name__ ( _lowerCamelCase : List[Any] , _lowerCamelCase : int , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : int , _lowerCamelCase : List[str] , _lowerCamelCase : int ): if got_ver is None or want_ver is None: raise ValueError( F'''Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider''' F''' reinstalling {pkg}.''' ) if not ops[op](version.parse(_lowerCamelCase ) , version.parse(_lowerCamelCase ) ): raise ImportError( F'''{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}''' ) def __magic_name__ ( _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ): __a : Optional[int] = F'''\n{hint}''' if hint is not None else """""" # non-versioned check if re.match(r"""^[\w_\-\d]+$""" , _lowerCamelCase ): __a : str = requirement, None, None else: __a : Dict = re.findall(r"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , _lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F''' got {requirement}''' ) __a : Union[str, Any] = match[0] __a : Dict = want_full.split(""",""" ) # there could be multiple requirements __a : List[str] = {} for w in want_range: __a : Dict = re.findall(r"""^([\s!=<>]{1,2})(.+)""" , _lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F''' but got {requirement}''' ) __a : Union[str, Any] = match[0] __a : Any = want_ver if op not in ops: raise ValueError(F'''{requirement}: need one of {list(ops.keys() )}, but got {op}''' ) # special case if pkg == "python": __a : Optional[Any] = """.""".join([str(_lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return # check if any version is installed try: __a : Any = importlib.metadata.version(_lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'''The \'{requirement}\' distribution was not found and is required by this application. {hint}''' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : int ): __a : Optional[int] = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(_lowerCamelCase , _lowerCamelCase )
706
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowercase__ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __snake_case ): _lowerCAmelCase = "linear" _lowerCAmelCase = "cosine" _lowerCAmelCase = "cosine_with_restarts" _lowerCAmelCase = "polynomial" _lowerCAmelCase = "constant" _lowerCAmelCase = "constant_with_warmup" _lowerCAmelCase = "piecewise_constant" def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int = -1 ): return LambdaLR(_lowerCamelCase , lambda _lowerCamelCase : 1 , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1.0 , _lowerCamelCase ) ) return 1.0 return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : str , _lowerCamelCase : int = -1 ): __a : Optional[int] = {} __a : Any = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __a , __a : int = rule_str.split(""":""" ) __a : Optional[int] = int(_lowerCamelCase ) __a : str = float(_lowerCamelCase ) __a : int = value __a : Dict = float(rule_list[-1] ) def create_rules_function(_lowerCamelCase : str , _lowerCamelCase : Tuple ): def rule_func(_lowerCamelCase : int ) -> float: __a : Optional[Any] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(_lowerCamelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __a : Optional[int] = create_rules_function(_lowerCamelCase , _lowerCamelCase ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , last_epoch=_lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : str=-1 ): def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0.5 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Any ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(_lowerCamelCase ) * 2.0 * progress )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Optimizer , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int = 1 , _lowerCamelCase : int = -1 ): def lr_lambda(_lowerCamelCase : Optional[int] ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) __a : Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(_lowerCamelCase ) * progress) % 1.0) )) ) return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]=1E-7 , _lowerCamelCase : Optional[int]=1.0 , _lowerCamelCase : Optional[int]=-1 ): __a : Union[str, Any] = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(_lowerCamelCase : int ): if current_step < num_warmup_steps: return float(_lowerCamelCase ) / float(max(1 , _lowerCamelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __a : Tuple = lr_init - lr_end __a : int = num_training_steps - num_warmup_steps __a : Optional[int] = 1 - (current_step - num_warmup_steps) / decay_steps __a : List[str] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __magic_name__ ( _lowerCamelCase : Union[str, SchedulerType] , _lowerCamelCase : Optimizer , _lowerCamelCase : Optional[str] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 1 , _lowerCamelCase : float = 1.0 , _lowerCamelCase : int = -1 , ): __a : int = SchedulerType(_lowerCamelCase ) __a : Optional[int] = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(_lowerCamelCase , last_epoch=_lowerCamelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(_lowerCamelCase , step_rules=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(_lowerCamelCase , num_warmup_steps=_lowerCamelCase , last_epoch=_lowerCamelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , num_cycles=_lowerCamelCase , last_epoch=_lowerCamelCase , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , power=_lowerCamelCase , last_epoch=_lowerCamelCase , ) return schedule_func( _lowerCamelCase , num_warmup_steps=_lowerCamelCase , num_training_steps=_lowerCamelCase , last_epoch=_lowerCamelCase )
63
0