code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''', } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = """transfo-xl""" UpperCamelCase_ : List[str] = ["""mems"""] UpperCamelCase_ : str = { """n_token""": """vocab_size""", """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, Any]=26_77_35 , SCREAMING_SNAKE_CASE_ : List[Any]=[2_00_00, 4_00_00, 20_00_00] , SCREAMING_SNAKE_CASE_ : int=10_24 , SCREAMING_SNAKE_CASE_ : Optional[int]=10_24 , SCREAMING_SNAKE_CASE_ : Optional[Any]=16 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=64 , SCREAMING_SNAKE_CASE_ : Tuple=40_96 , SCREAMING_SNAKE_CASE_ : int=4 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False , SCREAMING_SNAKE_CASE_ : Tuple=18 , SCREAMING_SNAKE_CASE_ : Dict=16_00 , SCREAMING_SNAKE_CASE_ : str=10_00 , SCREAMING_SNAKE_CASE_ : List[str]=True , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : Optional[Any]=0 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=-1 , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : Dict=0.1 , SCREAMING_SNAKE_CASE_ : str=0.0 , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : List[Any]="normal" , SCREAMING_SNAKE_CASE_ : Dict=0.01 , SCREAMING_SNAKE_CASE_ : Any=0.01 , SCREAMING_SNAKE_CASE_ : Dict=0.02 , SCREAMING_SNAKE_CASE_ : Any=1E-5 , SCREAMING_SNAKE_CASE_ : int=0 , **SCREAMING_SNAKE_CASE_ : List[Any] , ) -> Optional[Any]: '''simple docstring''' A: Optional[Any] = vocab_size A: Optional[Any] = [] self.cutoffs.extend(SCREAMING_SNAKE_CASE_ ) if proj_share_all_but_first: A: Union[str, Any] = [False] + [True] * len(self.cutoffs ) else: A: Any = [False] + [False] * len(self.cutoffs ) A: Tuple = d_model A: Union[str, Any] = d_embed A: Tuple = d_head A: Optional[int] = d_inner A: str = div_val A: Any = pre_lnorm A: Dict = n_layer A: Dict = n_head A: Union[str, Any] = mem_len A: str = same_length A: str = attn_type A: Optional[Any] = clamp_len A: Any = sample_softmax A: int = adaptive A: List[str] = dropout A: Tuple = dropatt A: List[str] = untie_r A: Optional[Any] = init A: Optional[int] = init_range A: Dict = proj_init_std A: Optional[int] = init_std A: Dict = layer_norm_epsilon super().__init__(eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def _snake_case ( self : Tuple ) -> Any: '''simple docstring''' logger.info(f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Dict ) -> int: '''simple docstring''' raise NotImplementedError( f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
369
'''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> int: '''simple docstring''' A: Tuple = None A: Dict = None A: Optional[int] = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: str = len(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = None def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ) -> str: '''simple docstring''' if sources is int: A: Union[str, Any] = [sources] if sinks is int: A: Tuple = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return A: List[str] = sources[0] A: Optional[int] = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: A: Any = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A: Dict = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A: Optional[Any] = max_input_flow A: Optional[Any] = 0 A: str = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A: Optional[Any] = max_input_flow A: str = size - 1 def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple: '''simple docstring''' A: Optional[Any] = algorithm(self ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: '''simple docstring''' A: str = flow_network A: List[str] = flow_network.verticesCount A: Dict = flow_network.sourceIndex A: Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A: str = flow_network.graph A: str = False def _snake_case ( self : int ) -> Union[str, Any]: '''simple docstring''' if not self.executed: self._algorithm() A: str = True def _snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' pass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result A: Any = -1 def _snake_case ( self : List[str] ) -> Optional[Any]: '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [[0] * self.verticies_count for i in range(self.verticies_count )] A: Any = [0] * self.verticies_count A: Optional[Any] = [0] * self.verticies_count def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' A: Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A: str = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A: Dict = 0 while i < len(SCREAMING_SNAKE_CASE_ ): A: Any = vertices_list[i] A: str = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) A: Tuple = 0 else: i += 1 A: Tuple = sum(self.preflow[self.source_index] ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: '''simple docstring''' A: Optional[int] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str ) -> int: '''simple docstring''' A: Optional[Any] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A: List[Any] = self.heights[to_index] if min_height is not None: A: int = min_height + 1 if __name__ == "__main__": UpperCamelCase = [0] UpperCamelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCamelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCamelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCamelCase = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase=False ) -> Optional[int]: if isinstance(__lowercase , __lowercase ) and isinstance(__lowercase , __lowercase ): A: Union[str, Any] = len(set_a.intersection(__lowercase ) ) if alternative_union: A: List[Any] = len(__lowercase ) + len(__lowercase ) else: A: List[str] = len(set_a.union(__lowercase ) ) return intersection / union if isinstance(__lowercase , (list, tuple) ) and isinstance(__lowercase , (list, tuple) ): A: Dict = [element for element in set_a if element in set_b] if alternative_union: A: Union[str, Any] = len(__lowercase ) + len(__lowercase ) return len(__lowercase ) / union else: A: Dict = set_a + [element for element in set_b if element not in set_a] return len(__lowercase ) / len(__lowercase ) return len(__lowercase ) / len(__lowercase ) return None if __name__ == "__main__": UpperCamelCase = {'''a''', '''b''', '''c''', '''d''', '''e'''} UpperCamelCase = {'''c''', '''d''', '''e''', '''f''', '''h''', '''i'''} print(jaccard_similarity(set_a, set_b))
370
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
334
0
'''simple docstring''' import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : Optional[int] ) -> str: '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(SCREAMING_SNAKE_CASE_ ): A: int = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Dict = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Any ) -> int: '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: with self.subTest(SCREAMING_SNAKE_CASE_ ): A: Any = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Optional[int] = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Optional[int] ) -> List[Any]: '''simple docstring''' for model_name in ["bert-base-cased", "bert-large-uncased"]: A: List[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) A: Dict = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = tokenizer('''Do you support jax jitted function?''' , return_tensors=TensorType.JAX ) @jax.jit def eval(**SCREAMING_SNAKE_CASE_ : int ): return model(**SCREAMING_SNAKE_CASE_ ) eval(**SCREAMING_SNAKE_CASE_ ).block_until_ready() @slow def _snake_case ( self : Any ) -> Dict: '''simple docstring''' for model_name in ["roberta-base", "roberta-large"]: A: Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = FlaxRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer('''Do you support jax jitted function?''' , return_tensors=TensorType.JAX ) @jax.jit def eval(**SCREAMING_SNAKE_CASE_ : int ): return model(**SCREAMING_SNAKE_CASE_ ) eval(**SCREAMING_SNAKE_CASE_ ).block_until_ready() def _snake_case ( self : Any ) -> Any: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''bert-base is not a local folder and is not a valid model identifier''' ): A: str = FlaxAutoModel.from_pretrained('''bert-base''' ) def _snake_case ( self : Any ) -> Any: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): A: Optional[Any] = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , revision='''aaaaaa''' ) def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack''' , ): A: Dict = FlaxAutoModel.from_pretrained('''hf-internal-testing/config-no-model''' ) def _snake_case ( self : Optional[int] ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , '''Use `from_pt=True` to load this model''' ): A: int = FlaxAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only''' )
371
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = DebertaTokenizer UpperCamelCase_ : List[str] = True UpperCamelCase_ : int = DebertaTokenizerFast def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A: Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] A: int = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A: Union[str, Any] = {'''unk_token''': '''[UNK]'''} A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: str = 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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : int , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = '''lower newer''' A: str = '''lower newer''' return input_text, output_text def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: str = self.get_tokenizer() A: Any = '''lower newer''' A: Dict = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] A: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokens + [tokenizer.unk_token] A: int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' A: str = self.get_tokenizer() A: List[str] = tokenizer('''Hello''' , '''World''' ) A: Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Tuple ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) A: int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _snake_case ( self : Tuple ) -> Dict: '''simple docstring''' A: int = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: A: List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Dict = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] A: Dict = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: Any = [tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) for seq in encoding['''input_ids''']] # fmt: off A: Any = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on A: Optional[int] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , SCREAMING_SNAKE_CASE_ ) for expected, decoded in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) UpperCamelCase = logging.getLogger(__name__) UpperCamelCase = tf.data.AUTOTUNE def SCREAMING_SNAKE_CASE( ) -> Union[str, Any]: A: List[Any] = argparse.ArgumentParser(description='''Train a masked language model on TPU.''' ) parser.add_argument( '''--pretrained_model_config''' , type=__lowercase , default='''roberta-base''' , help='''The model config to use. Note that we don\'t copy the model\'s weights, only the config!''' , ) parser.add_argument( '''--tokenizer''' , type=__lowercase , default='''unigram-tokenizer-wikitext''' , help='''The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model\'s vocab size.''' , ) parser.add_argument( '''--per_replica_batch_size''' , type=__lowercase , default=8 , help='''Batch size per TPU core.''' , ) parser.add_argument( '''--no_tpu''' , action='''store_true''' , help='''If set, run on CPU and don\'t try to initialize a TPU. Useful for debugging on non-TPU instances.''' , ) parser.add_argument( '''--tpu_name''' , type=__lowercase , help='''Name of TPU resource to initialize. Should be blank on Colab, and \'local\' on TPU VMs.''' , default='''local''' , ) parser.add_argument( '''--tpu_zone''' , type=__lowercase , help='''Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.''' , ) parser.add_argument( '''--gcp_project''' , type=__lowercase , help='''Google cloud project name. Only used for non-Colab TPU nodes.''' ) parser.add_argument( '''--bfloat16''' , action='''store_true''' , help='''Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.''' , ) parser.add_argument( '''--train_dataset''' , type=__lowercase , help='''Path to training dataset to load. If the path begins with `gs://`''' ''' then the dataset will be loaded from a Google Cloud Storage bucket.''' , ) parser.add_argument( '''--shuffle_buffer_size''' , type=__lowercase , default=2**1_8 , help='''Size of the shuffle buffer (in samples)''' , ) parser.add_argument( '''--eval_dataset''' , type=__lowercase , help='''Path to evaluation dataset to load. If the path begins with `gs://`''' ''' then the dataset will be loaded from a Google Cloud Storage bucket.''' , ) parser.add_argument( '''--num_epochs''' , type=__lowercase , default=1 , help='''Number of epochs to train for.''' , ) parser.add_argument( '''--learning_rate''' , type=__lowercase , default=1E-4 , help='''Learning rate to use for training.''' , ) parser.add_argument( '''--weight_decay_rate''' , type=__lowercase , default=1E-3 , help='''Weight decay rate to use for training.''' , ) parser.add_argument( '''--max_length''' , type=__lowercase , default=5_1_2 , help='''Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py''' , ) parser.add_argument( '''--mlm_probability''' , type=__lowercase , default=0.1_5 , help='''Fraction of tokens to mask during training.''' , ) parser.add_argument('''--output_dir''' , type=__lowercase , required=__lowercase , help='''Path to save model checkpoints to.''' ) parser.add_argument('''--hub_model_id''' , type=__lowercase , help='''Model ID to upload to on the Hugging Face Hub.''' ) A: Dict = parser.parse_args() return args def SCREAMING_SNAKE_CASE( __lowercase ) -> Optional[int]: try: if args.tpu_name: A: Optional[int] = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: A: int = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( '''Couldn\'t connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or ''' '''--gcp_project. When running on a TPU VM, use --tpu_name local.''' ) tf.config.experimental_connect_to_cluster(__lowercase ) tf.tpu.experimental.initialize_tpu_system(__lowercase ) return tpu def SCREAMING_SNAKE_CASE( __lowercase ) -> Optional[Any]: A: str = 0 for file in file_list: A: Any = file.split('''/''' )[-1] A: Any = re.search(r'''-\d+-(\d+)\.tfrecord''' , __lowercase ).group(1 ) A: int = int(__lowercase ) num_samples += sample_count return num_samples def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase=None ) -> Dict: A: List[Any] = count_samples(__lowercase ) A: Tuple = tf.data.Dataset.from_tensor_slices(__lowercase ) if shuffle: A: str = dataset.shuffle(len(__lowercase ) ) A: List[str] = tf.data.TFRecordDataset(__lowercase , num_parallel_reads=__lowercase ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here A: Optional[Any] = dataset.apply(tf.data.experimental.assert_cardinality(__lowercase ) ) A: Optional[int] = dataset.map(__lowercase , num_parallel_calls=__lowercase ) if shuffle: assert shuffle_buffer_size is not None A: Optional[Any] = dataset.shuffle(args.shuffle_buffer_size ) A: List[str] = dataset.batch(__lowercase , drop_remainder=__lowercase ) A: int = dataset.map(__lowercase , num_parallel_calls=__lowercase ) A: List[str] = dataset.prefetch(__lowercase ) return dataset def SCREAMING_SNAKE_CASE( __lowercase ) -> Tuple: if not args.no_tpu: A: List[str] = initialize_tpu(__lowercase ) A: Dict = tf.distribute.TPUStrategy(__lowercase ) else: A: List[Any] = tf.distribute.OneDeviceStrategy(device='''/gpu:0''' ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy('''mixed_bfloat16''' ) A: List[Any] = AutoTokenizer.from_pretrained(args.tokenizer ) A: List[Any] = AutoConfig.from_pretrained(args.pretrained_model_config ) A: Optional[int] = tokenizer.vocab_size A: Optional[int] = tf.io.gfile.glob(os.path.join(args.train_dataset , '''*.tfrecord''' ) ) if not training_records: raise ValueError(F"""No .tfrecord files found in {args.train_dataset}.""" ) A: Union[str, Any] = tf.io.gfile.glob(os.path.join(args.eval_dataset , '''*.tfrecord''' ) ) if not eval_records: raise ValueError(F"""No .tfrecord files found in {args.eval_dataset}.""" ) A: int = count_samples(__lowercase ) A: int = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) A: Tuple = steps_per_epoch * args.num_epochs with strategy.scope(): A: Optional[Any] = TFAutoModelForMaskedLM.from_config(__lowercase ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built A: int = create_optimizer( num_train_steps=__lowercase , num_warmup_steps=total_train_steps // 2_0 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=__lowercase , metrics=['''accuracy'''] ) def decode_fn(__lowercase ): A: Dict = { '''input_ids''': tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), '''attention_mask''': tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(__lowercase , __lowercase ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. A: Optional[int] = DataCollatorForLanguageModeling( tokenizer=__lowercase , mlm_probability=args.mlm_probability , mlm=__lowercase , return_tensors='''tf''' ) def mask_with_collator(__lowercase ): # TF really needs an isin() function A: Dict = ( ~tf.cast(batch['''attention_mask'''] , tf.bool ) | (batch['''input_ids'''] == tokenizer.cls_token_id) | (batch['''input_ids'''] == tokenizer.sep_token_id) ) A: Tuple = data_collator.tf_mask_tokens( batch['''input_ids'''] , vocab_size=len(__lowercase ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=__lowercase , ) return batch A: Union[str, Any] = args.per_replica_batch_size * strategy.num_replicas_in_sync A: List[str] = prepare_dataset( __lowercase , decode_fn=__lowercase , mask_fn=__lowercase , batch_size=__lowercase , shuffle=__lowercase , shuffle_buffer_size=args.shuffle_buffer_size , ) A: Any = prepare_dataset( __lowercase , decode_fn=__lowercase , mask_fn=__lowercase , batch_size=__lowercase , shuffle=__lowercase , ) A: int = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=__lowercase ) ) model.fit( __lowercase , validation_data=__lowercase , epochs=args.num_epochs , callbacks=__lowercase , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": UpperCamelCase = parse_args() main(args)
350
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] , 1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
334
0
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) UpperCamelCase = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='''relu''') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='''relu''')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='''relu''')) classifier.add(layers.Dense(units=1, activation='''sigmoid''')) # Compiling the CNN classifier.compile( optimizer='''adam''', loss='''binary_crossentropy''', metrics=['''accuracy'''] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') UpperCamelCase = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) UpperCamelCase = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) UpperCamelCase = train_datagen.flow_from_directory( '''dataset/training_set''', target_size=(64, 64), batch_size=32, class_mode='''binary''' ) UpperCamelCase = test_datagen.flow_from_directory( '''dataset/test_set''', target_size=(64, 64), batch_size=32, class_mode='''binary''' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('''cnn.h5''') # Part 3 - Making new predictions UpperCamelCase = tf.keras.preprocessing.image.load_img( '''dataset/single_prediction/image.png''', target_size=(64, 64) ) UpperCamelCase = tf.keras.preprocessing.image.img_to_array(test_image) UpperCamelCase = np.expand_dims(test_image, axis=0) UpperCamelCase = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: UpperCamelCase = '''Normal''' if result[0][0] == 1: UpperCamelCase = '''Abnormality detected'''
351
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } UpperCamelCase = { '''camembert-base''': 512, } UpperCamelCase = '''▁''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : str = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : int = CamembertTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : str="<s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE_ : List[Any]="</s>" , SCREAMING_SNAKE_CASE_ : int="<s>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<unk>" , SCREAMING_SNAKE_CASE_ : str="<pad>" , SCREAMING_SNAKE_CASE_ : List[str]="<mask>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , **SCREAMING_SNAKE_CASE_ : Any , ) -> Any: '''simple docstring''' A: Tuple = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Any = vocab_file A: Any = False if not self.vocab_file else True def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''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: List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: List[str] = [self.sep_token_id] A: Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return A: Dict = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
334
0
'''simple docstring''' import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets UpperCamelCase = '''\ @inproceedings{pillutla-etal:mauve:neurips2021, title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers}, author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid}, booktitle = {NeurIPS}, year = {2021} } ''' UpperCamelCase = '''\ MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure. MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences. For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021). This metrics is a wrapper around the official implementation of MAUVE: https://github.com/krishnap25/mauve ''' UpperCamelCase = ''' Calculates MAUVE scores between two lists of generated text and reference text. Args: predictions: list of generated text to score. Each predictions should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. Optional Args: num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1 kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9 kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5 kmeans_max_iter: maximum number of k-means iterations. Default 500 featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\']. device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU max_text_length: maximum number of tokens to consider. Default 1024 divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25 mauve_scaling_factor: "c" from the paper. Default 5. verbose: If True (default), print running time updates seed: random seed to initialize k-means cluster assignments. Returns: mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer, frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer, divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve, p_hist: a discrete distribution, which is a quantized version of the text distribution p_text, q_hist: same as above, but with q_text. Examples: >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest >>> import datasets >>> mauve = datasets.load_metric(\'mauve\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP >>> print(out.mauve) # doctest: +SKIP 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : List[Any]="auto" , SCREAMING_SNAKE_CASE_ : str=-1 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.9 , SCREAMING_SNAKE_CASE_ : Dict=5 , SCREAMING_SNAKE_CASE_ : Optional[int]=5_00 , SCREAMING_SNAKE_CASE_ : str="gpt2-large" , SCREAMING_SNAKE_CASE_ : List[str]=-1 , SCREAMING_SNAKE_CASE_ : List[str]=10_24 , SCREAMING_SNAKE_CASE_ : str=25 , SCREAMING_SNAKE_CASE_ : List[Any]=5 , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : str=25 , ) -> List[Any]: '''simple docstring''' A = compute_mauve( p_text=SCREAMING_SNAKE_CASE_ , q_text=SCREAMING_SNAKE_CASE_ , p_features=SCREAMING_SNAKE_CASE_ , q_features=SCREAMING_SNAKE_CASE_ , p_tokens=SCREAMING_SNAKE_CASE_ , q_tokens=SCREAMING_SNAKE_CASE_ , num_buckets=SCREAMING_SNAKE_CASE_ , pca_max_data=SCREAMING_SNAKE_CASE_ , kmeans_explained_var=SCREAMING_SNAKE_CASE_ , kmeans_num_redo=SCREAMING_SNAKE_CASE_ , kmeans_max_iter=SCREAMING_SNAKE_CASE_ , featurize_model_name=SCREAMING_SNAKE_CASE_ , device_id=SCREAMING_SNAKE_CASE_ , max_text_length=SCREAMING_SNAKE_CASE_ , divergence_curve_discretization_size=SCREAMING_SNAKE_CASE_ , mauve_scaling_factor=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , seed=SCREAMING_SNAKE_CASE_ , ) return out
352
'''simple docstring''' import os from distutils.util import strtobool def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[Any]: for e in env_keys: A: Dict = int(os.environ.get(__lowercase , -1 ) ) if val >= 0: return val return default def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=False ) -> List[str]: A: str = os.environ.get(__lowercase , str(__lowercase ) ) return strtobool(__lowercase ) == 1 # As its name indicates `strtobool` actually returns an int... def SCREAMING_SNAKE_CASE( __lowercase , __lowercase="no" ) -> str: A: Optional[int] = os.environ.get(__lowercase , str(__lowercase ) ) return value
334
0
'''simple docstring''' import requests UpperCamelCase = '''YOUR API KEY''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = giphy_api_key ) -> list: A: int = '''+'''.join(query.split() ) A: Union[str, Any] = F"""https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}""" A: str = requests.get(__lowercase ).json()['''data'''] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('''\n'''.join(get_gifs('''space ship''')))
353
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() UpperCamelCase = logging.get_logger('''transformers.models.encodec''') UpperCamelCase = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } UpperCamelCase = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } UpperCamelCase = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } UpperCamelCase = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } UpperCamelCase = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } UpperCamelCase = [] UpperCamelCase = [] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: for attribute in key.split('''.''' ): A: Union[str, Any] = getattr(__lowercase , __lowercase ) if weight_type is not None: A: Tuple = getattr(__lowercase , __lowercase ).shape else: A: str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": A: Dict = value elif weight_type == "weight_g": A: Tuple = value elif weight_type == "weight_v": A: Any = value elif weight_type == "bias": A: str = value elif weight_type == "running_mean": A: List[Any] = value elif weight_type == "running_var": A: Dict = value elif weight_type == "num_batches_tracked": A: List[str] = value elif weight_type == "weight_ih_l0": A: Dict = value elif weight_type == "weight_hh_l0": A: Optional[int] = value elif weight_type == "bias_ih_l0": A: List[Any] = value elif weight_type == "bias_hh_l0": A: str = value elif weight_type == "weight_ih_l1": A: Optional[int] = value elif weight_type == "weight_hh_l1": A: int = value elif weight_type == "bias_ih_l1": A: Optional[Any] = value elif weight_type == "bias_hh_l1": A: str = value else: A: Optional[int] = value logger.info(F"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Optional[Any]: for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: A , A: Any = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Tuple: A: Any = [] if model_name == "encodec_24khz" or "encodec_32khz": A: List[str] = MAPPING_24K elif model_name == "encodec_48khz": A: List[Any] = MAPPING_48K else: raise ValueError(F"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(__lowercase , __lowercase ): logger.info(F"""{name} was ignored""" ) continue A: Optional[int] = False for key, mapped_key in MAPPING.items(): if "*" in key: A , A: Optional[int] = key.split('''.*.''' ) if prefix in name and suffix in name: A: str = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('''embed''' ) and name.endswith('''embed_avg''' ): continue A: Optional[Any] = True if "*" in mapped_key: A: Any = name.split(__lowercase )[0].split('''.''' )[-2] A: Tuple = mapped_key.replace('''*''' , __lowercase ) if "weight_g" in name: A: str = '''weight_g''' elif "weight_v" in name: A: List[Any] = '''weight_v''' elif "weight_ih_l0" in name: A: Dict = '''weight_ih_l0''' elif "weight_hh_l0" in name: A: int = '''weight_hh_l0''' elif "bias_ih_l0" in name: A: Union[str, Any] = '''bias_ih_l0''' elif "bias_hh_l0" in name: A: Tuple = '''bias_hh_l0''' elif "weight_ih_l1" in name: A: int = '''weight_ih_l1''' elif "weight_hh_l1" in name: A: Optional[Any] = '''weight_hh_l1''' elif "bias_ih_l1" in name: A: Dict = '''bias_ih_l1''' elif "bias_hh_l1" in name: A: str = '''bias_hh_l1''' elif "bias" in name: A: Union[str, Any] = '''bias''' elif "weight" in name: A: Dict = '''weight''' elif "running_mean" in name: A: Tuple = '''running_mean''' elif "running_var" in name: A: Any = '''running_var''' elif "num_batches_tracked" in name: A: str = '''num_batches_tracked''' else: A: Tuple = None set_recursively(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) continue if not is_used: unused_weights.append(__lowercase ) logger.warning(F"""Unused weights: {unused_weights}""" ) @torch.no_grad() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase=None , __lowercase=None , ) -> Dict: if config_path is not None: A: Tuple = EncodecConfig.from_pretrained(__lowercase ) else: A: Union[str, Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": A: Union[str, Any] = [8, 5, 4, 4] A: Dict = [2.2] A: List[Any] = 6_4 A: Optional[Any] = 3_2_0_0_0 A: List[Any] = 2_0_4_8 A: Optional[Any] = False A: int = False A: Union[str, Any] = False elif model_name == "encodec_48khz": A: Optional[int] = [8, 5, 4, 2] A: List[Any] = [3.0, 6.0, 1_2.0, 2_4.0] A: List[Any] = 4_8_0_0_0 A: int = 2 A: List[Any] = False A: Any = '''time_group_norm''' A: Optional[Any] = True A: Any = 1.0 A: Any = 0.0_1 else: raise ValueError(F"""Unknown model name: {model_name}""" ) A: str = EncodecModel(__lowercase ) A: Optional[Any] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__lowercase ) A: Union[str, Any] = torch.load(__lowercase ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights A: Optional[int] = original_checkpoint['''best_state'''] recursively_load_weights(__lowercase , __lowercase , __lowercase ) model.save_pretrained(__lowercase ) if repo_id: print('''Pushing to the hub...''' ) feature_extractor.push_to_hub(__lowercase ) model.push_to_hub(__lowercase ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) UpperCamelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
334
0
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = DebertaTokenizer UpperCamelCase_ : List[str] = True UpperCamelCase_ : int = DebertaTokenizerFast def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A: Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] A: int = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A: Union[str, Any] = {'''unk_token''': '''[UNK]'''} A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: str = 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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : int , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = '''lower newer''' A: str = '''lower newer''' return input_text, output_text def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: str = self.get_tokenizer() A: Any = '''lower newer''' A: Dict = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] A: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokens + [tokenizer.unk_token] A: int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' A: str = self.get_tokenizer() A: List[str] = tokenizer('''Hello''' , '''World''' ) A: Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Tuple ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) A: int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _snake_case ( self : Tuple ) -> Dict: '''simple docstring''' A: int = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: A: List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Dict = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] A: Dict = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: Any = [tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) for seq in encoding['''input_ids''']] # fmt: off A: Any = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on A: Optional[int] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , SCREAMING_SNAKE_CASE_ ) for expected, decoded in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
354
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : Optional[Any] = XGLMConfig UpperCamelCase_ : str = {} UpperCamelCase_ : int = """gelu""" def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int=14 , SCREAMING_SNAKE_CASE_ : Any=7 , SCREAMING_SNAKE_CASE_ : List[str]=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , SCREAMING_SNAKE_CASE_ : int=True , SCREAMING_SNAKE_CASE_ : str=99 , SCREAMING_SNAKE_CASE_ : Dict=32 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE_ : Tuple=4 , SCREAMING_SNAKE_CASE_ : Tuple=37 , SCREAMING_SNAKE_CASE_ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE_ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE_ : str=0.1 , SCREAMING_SNAKE_CASE_ : Optional[int]=5_12 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.02 , ) -> List[Any]: '''simple docstring''' A: Union[str, Any] = parent A: Optional[Any] = batch_size A: Optional[int] = seq_length A: Union[str, Any] = is_training A: str = use_input_mask A: int = use_labels A: List[str] = vocab_size A: Optional[int] = d_model A: int = num_hidden_layers A: Optional[Any] = num_attention_heads A: Any = ffn_dim A: Optional[int] = activation_function A: Optional[int] = activation_dropout A: Optional[int] = attention_dropout A: Tuple = max_position_embeddings A: Optional[int] = initializer_range A: List[Any] = None A: List[Any] = 0 A: Tuple = 2 A: Optional[Any] = 1 def _snake_case ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return XGLMConfig.from_pretrained('''facebook/xglm-564M''' ) def _snake_case ( self : List[str] ) -> List[Any]: '''simple docstring''' A: Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) A: List[str] = None if self.use_input_mask: A: Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A: List[Any] = self.get_config() A: str = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def _snake_case ( self : Union[str, Any] ) -> str: '''simple docstring''' return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE_ , ) def _snake_case ( self : str ) -> str: '''simple docstring''' A: Any = self.prepare_config_and_inputs() ( A ): Union[str, Any] = config_and_inputs A: Optional[int] = { '''input_ids''': input_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_tf class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () UpperCamelCase_ : Any = (TFXGLMForCausalLM,) if is_tf_available() else () UpperCamelCase_ : Union[str, Any] = ( {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {} ) UpperCamelCase_ : List[Any] = False UpperCamelCase_ : List[Any] = False UpperCamelCase_ : Tuple = False def _snake_case ( self : Union[str, Any] ) -> int: '''simple docstring''' A: Dict = TFXGLMModelTester(self ) A: Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , n_embd=37 ) def _snake_case ( self : int ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @slow def _snake_case ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A: Optional[int] = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.''' ) def _snake_case ( self : str ) -> Optional[int]: '''simple docstring''' super().test_resize_token_embeddings() @require_tf class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Dict=True ) -> str: '''simple docstring''' A: List[Any] = TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) A: Optional[int] = tf.convert_to_tensor([[2, 2_68, 98_65]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off A: List[str] = [2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81] # fmt: on A: List[Any] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Union[str, Any] ) -> str: '''simple docstring''' A: str = XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) A: List[str] = TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) tf.random.set_seed(0 ) A: Optional[int] = tokenizer('''Today is a nice day and''' , return_tensors='''tf''' ) A: Union[str, Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(''':/CPU:0''' ): A: Any = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ , seed=[7, 0] ) A: str = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = ( '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due''' ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Dict ) -> Optional[Any]: '''simple docstring''' A: Dict = TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) A: Any = XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) A: List[str] = '''left''' # use different length sentences to test batching A: List[str] = [ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When''', '''Hello, my dog is a little''', ] A: List[str] = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='''tf''' , padding=SCREAMING_SNAKE_CASE_ ) A: Tuple = inputs['''input_ids'''] A: Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs['''attention_mask'''] , max_new_tokens=12 ) A: Union[str, Any] = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids A: str = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_new_tokens=12 ) A: Optional[int] = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids A: List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_new_tokens=12 ) A: int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Any = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ''' '''a single''', '''Hello, my dog is a little bit of a shy one, but he is very friendly''', ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] )
355
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for data in source_data: for i, el in enumerate(__lowercase ): if len(__lowercase ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__lowercase ) ) return data_lists def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for dlist, weight in zip(__lowercase , __lowercase ): A: List[str] = min(__lowercase ) A: Union[str, Any] = max(__lowercase ) A: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: A: List[str] = F"""Invalid weight of {weight:f} provided""" raise ValueError(__lowercase ) score_lists.append(__lowercase ) return score_lists def SCREAMING_SNAKE_CASE( __lowercase ) -> list[float]: A: list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__lowercase ): A: str = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: Any = get_data(__lowercase ) A: str = calculate_each_score(__lowercase , __lowercase ) A: int = generate_final_scores(__lowercase ) # append scores to source data for i, ele in enumerate(__lowercase ): source_data[i].append(__lowercase ) return source_data
334
0
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = """""" UpperCamelCase_ : List[Any] = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[DatasetInfo] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> int: '''simple docstring''' super().__init__(self , **SCREAMING_SNAKE_CASE_ ) A: Tuple = repo_info A: int = token A: Optional[Any] = None def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self.dir_cache is None: A: Dict = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes A: Union[str, Any] = { '''name''': hf_file.rfilename, '''size''': None, '''type''': '''file''', } self.dir_cache.update( { str(SCREAMING_SNAKE_CASE_ ): {'''name''': str(SCREAMING_SNAKE_CASE_ ), '''size''': None, '''type''': '''directory'''} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str = "rb" , **SCREAMING_SNAKE_CASE_ : int , ) -> Any: '''simple docstring''' if not isinstance(self.repo_info , SCREAMING_SNAKE_CASE_ ): raise NotImplementedError(f"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) A: Union[str, Any] = hf_hub_url(self.repo_info.id , SCREAMING_SNAKE_CASE_ , revision=self.repo_info.sha ) return fsspec.open( SCREAMING_SNAKE_CASE_ , mode=SCREAMING_SNAKE_CASE_ , headers=get_authentication_headers_for_url(SCREAMING_SNAKE_CASE_ , use_auth_token=self.token ) , client_kwargs={'''trust_env''': True} , ).open() def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , **SCREAMING_SNAKE_CASE_ : int ) -> Dict: '''simple docstring''' self._get_dirs() A: Optional[Any] = self._strip_protocol(SCREAMING_SNAKE_CASE_ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=False , **SCREAMING_SNAKE_CASE_ : int ) -> List[str]: '''simple docstring''' self._get_dirs() A: int = PurePosixPath(path.strip('''/''' ) ) A: str = {} for p, f in self.dir_cache.items(): A: Dict = PurePosixPath(p.strip('''/''' ) ) A: Optional[Any] = p.parent if root == path: A: Dict = f A: Dict = list(paths.values() ) if detail: return out else: return sorted(f['''name'''] for f in out )
356
'''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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = DPRContextEncoderTokenizer class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Dict = VOCAB_FILES_NAMES UpperCamelCase_ : List[str] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Tuple = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Optional[int] = DPRQuestionEncoderTokenizer UpperCamelCase = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) UpperCamelCase = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) UpperCamelCase = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ : '''simple docstring''' def __call__( self : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchEncoding: '''simple docstring''' if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) elif titles is None or texts is None: A: Union[str, Any] = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = titles if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [titles] A: Optional[Any] = texts if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [texts] A: str = len(SCREAMING_SNAKE_CASE_ ) A: List[Any] = questions if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [questions] * n_passages assert len(SCREAMING_SNAKE_CASE_ ) == len( SCREAMING_SNAKE_CASE_ ), f"""There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE_ )} titles and {len(SCREAMING_SNAKE_CASE_ )} texts.""" A: Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: Dict = super().__call__(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: str = { '''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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] } if return_attention_mask is not False: A: Union[str, Any] = [] 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: Optional[Any] = attention_mask return self.pad(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : BatchEncoding , SCREAMING_SNAKE_CASE_ : DPRReaderOutput , SCREAMING_SNAKE_CASE_ : int = 16 , SCREAMING_SNAKE_CASE_ : int = 64 , SCREAMING_SNAKE_CASE_ : int = 4 , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Any = reader_input['''input_ids'''] A , A , A: str = reader_output[:3] A: str = len(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = sorted(range(SCREAMING_SNAKE_CASE_ ) , reverse=SCREAMING_SNAKE_CASE_ , key=relevance_logits.__getitem__ ) A: List[DPRReaderOutput] = [] for doc_id in sorted_docs: A: List[str] = 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: Union[str, Any] = sequence_ids.index(self.pad_token_id ) else: A: int = len(SCREAMING_SNAKE_CASE_ ) A: Dict = 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=SCREAMING_SNAKE_CASE_ , top_spans=SCREAMING_SNAKE_CASE_ , ) 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=SCREAMING_SNAKE_CASE_ , start_index=SCREAMING_SNAKE_CASE_ , end_index=SCREAMING_SNAKE_CASE_ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE_ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Union[str, Any] = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE_ ): 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: Any = sorted(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : x[1] , reverse=SCREAMING_SNAKE_CASE_ ) A: Dict = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]""" A: int = 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(SCREAMING_SNAKE_CASE_ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] = READER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = READER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : Optional[Any] = DPRReaderTokenizer
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> int: if len(__lowercase ) != len(__lowercase ): raise ValueError('''String lengths must match!''' ) A: str = 0 for chara, chara in zip(__lowercase , __lowercase ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
357
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed UpperCamelCase = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def SCREAMING_SNAKE_CASE( __lowercase ) -> Any: assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[str]: if args.student_type == "roberta": A: Optional[int] = False elif args.student_type == "gpt2": A: List[Any] = False def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[Any]: if args.student_type == "roberta": A: Union[str, Any] = False def SCREAMING_SNAKE_CASE( ) -> Union[str, Any]: A: str = argparse.ArgumentParser(description='''Training''' ) parser.add_argument('''--force''' , action='''store_true''' , help='''Overwrite dump_path if it already exists.''' ) parser.add_argument( '''--dump_path''' , type=__lowercase , required=__lowercase , help='''The output directory (log, checkpoints, parameters, etc.)''' ) parser.add_argument( '''--data_file''' , type=__lowercase , required=__lowercase , help='''The binarized file (tokenized + tokens_to_ids) and grouped by sequence.''' , ) parser.add_argument( '''--student_type''' , type=__lowercase , choices=['''distilbert''', '''roberta''', '''gpt2'''] , required=__lowercase , help='''The student type (DistilBERT, RoBERTa).''' , ) parser.add_argument('''--student_config''' , type=__lowercase , required=__lowercase , help='''Path to the student configuration.''' ) parser.add_argument( '''--student_pretrained_weights''' , default=__lowercase , type=__lowercase , help='''Load student initialization checkpoint.''' ) parser.add_argument( '''--teacher_type''' , choices=['''bert''', '''roberta''', '''gpt2'''] , required=__lowercase , help='''Teacher type (BERT, RoBERTa).''' ) parser.add_argument('''--teacher_name''' , type=__lowercase , required=__lowercase , help='''The teacher model.''' ) parser.add_argument('''--temperature''' , default=2.0 , type=__lowercase , help='''Temperature for the softmax temperature.''' ) parser.add_argument( '''--alpha_ce''' , default=0.5 , type=__lowercase , help='''Linear weight for the distillation loss. Must be >=0.''' ) parser.add_argument( '''--alpha_mlm''' , default=0.0 , type=__lowercase , help='''Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.''' , ) parser.add_argument('''--alpha_clm''' , default=0.5 , type=__lowercase , help='''Linear weight for the CLM loss. Must be >=0.''' ) parser.add_argument('''--alpha_mse''' , default=0.0 , type=__lowercase , help='''Linear weight of the MSE loss. Must be >=0.''' ) parser.add_argument( '''--alpha_cos''' , default=0.0 , type=__lowercase , help='''Linear weight of the cosine embedding loss. Must be >=0.''' ) parser.add_argument( '''--mlm''' , action='''store_true''' , help='''The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.''' ) parser.add_argument( '''--mlm_mask_prop''' , default=0.1_5 , type=__lowercase , help='''Proportion of tokens for which we need to make a prediction.''' , ) parser.add_argument('''--word_mask''' , default=0.8 , type=__lowercase , help='''Proportion of tokens to mask out.''' ) parser.add_argument('''--word_keep''' , default=0.1 , type=__lowercase , help='''Proportion of tokens to keep.''' ) parser.add_argument('''--word_rand''' , default=0.1 , type=__lowercase , help='''Proportion of tokens to randomly replace.''' ) parser.add_argument( '''--mlm_smoothing''' , default=0.7 , type=__lowercase , help='''Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).''' , ) parser.add_argument('''--token_counts''' , type=__lowercase , help='''The token counts in the data_file for MLM.''' ) parser.add_argument( '''--restrict_ce_to_mask''' , action='''store_true''' , help='''If true, compute the distillation loss only the [MLM] prediction distribution.''' , ) parser.add_argument( '''--freeze_pos_embs''' , action='''store_true''' , help='''Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.''' , ) parser.add_argument( '''--freeze_token_type_embds''' , action='''store_true''' , help='''Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.''' , ) parser.add_argument('''--n_epoch''' , type=__lowercase , default=3 , help='''Number of pass on the whole dataset.''' ) parser.add_argument('''--batch_size''' , type=__lowercase , default=5 , help='''Batch size (for each process).''' ) parser.add_argument( '''--group_by_size''' , action='''store_false''' , help='''If true, group sequences that have similar length into the same batch. Default is true.''' , ) parser.add_argument( '''--gradient_accumulation_steps''' , type=__lowercase , default=5_0 , help='''Gradient accumulation for larger training batches.''' , ) parser.add_argument('''--warmup_prop''' , default=0.0_5 , type=__lowercase , help='''Linear warmup proportion.''' ) parser.add_argument('''--weight_decay''' , default=0.0 , type=__lowercase , help='''Weight decay if we apply some.''' ) parser.add_argument('''--learning_rate''' , default=5E-4 , type=__lowercase , help='''The initial learning rate for Adam.''' ) parser.add_argument('''--adam_epsilon''' , default=1E-6 , type=__lowercase , help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--max_grad_norm''' , default=5.0 , type=__lowercase , help='''Max gradient norm.''' ) parser.add_argument('''--initializer_range''' , default=0.0_2 , type=__lowercase , help='''Random initialization range.''' ) parser.add_argument( '''--fp16''' , action='''store_true''' , help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''' , ) parser.add_argument( '''--fp16_opt_level''' , type=__lowercase , default='''O1''' , help=( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].''' '''See details at https://nvidia.github.io/apex/amp.html''' ) , ) parser.add_argument('''--n_gpu''' , type=__lowercase , default=1 , help='''Number of GPUs in the node.''' ) parser.add_argument('''--local_rank''' , type=__lowercase , default=-1 , help='''Distributed training - Local rank''' ) parser.add_argument('''--seed''' , type=__lowercase , default=5_6 , help='''Random seed''' ) parser.add_argument('''--log_interval''' , type=__lowercase , default=5_0_0 , help='''Tensorboard logging interval.''' ) parser.add_argument('''--checkpoint_interval''' , type=__lowercase , default=4_0_0_0 , help='''Checkpoint interval.''' ) A: List[str] = parser.parse_args() sanity_checks(__lowercase ) # ARGS # init_gpu_params(__lowercase ) set_seed(__lowercase ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( F"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" ''' itUse `--force` if you want to overwrite it''' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(F"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(F"""Param: {args}""" ) with open(os.path.join(args.dump_path , '''parameters.json''' ) , '''w''' ) as f: json.dump(vars(__lowercase ) , __lowercase , indent=4 ) git_log(args.dump_path ) A: Union[str, Any] = MODEL_CLASSES[args.student_type] A: int = MODEL_CLASSES[args.teacher_type] # TOKENIZER # A: Tuple = teacher_tokenizer_class.from_pretrained(args.teacher_name ) A: int = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): A: int = tokenizer.all_special_tokens.index(__lowercase ) A: Any = tokenizer.all_special_ids[idx] logger.info(F"""Special tokens {special_tok_ids}""" ) A: Tuple = special_tok_ids A: Optional[int] = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(F"""Loading data from {args.data_file}""" ) with open(args.data_file , '''rb''' ) as fp: A: Any = pickle.load(__lowercase ) if args.mlm: logger.info(F"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , '''rb''' ) as fp: A: Optional[int] = pickle.load(__lowercase ) A: str = np.maximum(__lowercase , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): A: Any = 0.0 # do not predict special tokens A: Optional[Any] = torch.from_numpy(__lowercase ) else: A: Tuple = None A: Optional[int] = LmSeqsDataset(params=__lowercase , data=__lowercase ) logger.info('''Data loader created.''' ) # STUDENT # logger.info(F"""Loading student config from {args.student_config}""" ) A: Tuple = student_config_class.from_pretrained(args.student_config ) A: Any = True if args.student_pretrained_weights is not None: logger.info(F"""Loading pretrained weights from {args.student_pretrained_weights}""" ) A: str = student_model_class.from_pretrained(args.student_pretrained_weights , config=__lowercase ) else: A: int = student_model_class(__lowercase ) if args.n_gpu > 0: student.to(F"""cuda:{args.local_rank}""" ) logger.info('''Student loaded.''' ) # TEACHER # A: List[Any] = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__lowercase ) if args.n_gpu > 0: teacher.to(F"""cuda:{args.local_rank}""" ) logger.info(F"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__lowercase , __lowercase ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__lowercase , __lowercase ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() A: str = Distiller( params=__lowercase , dataset=__lowercase , token_probs=__lowercase , student=__lowercase , teacher=__lowercase ) distiller.train() logger.info('''Let\'s go get some drinks.''' ) if __name__ == "__main__": main()
358
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' pass class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> None: '''simple docstring''' A: Any = data A: Node | None = None def __iter__( self : Optional[int] ) -> List[str]: '''simple docstring''' A: List[str] = self A: Dict = [] while node: if node in visited: raise ContainsLoopError visited.append(SCREAMING_SNAKE_CASE_ ) yield node.data A: str = node.next_node @property def _snake_case ( self : List[str] ) -> bool: '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": UpperCamelCase = Node(1) UpperCamelCase = Node(2) UpperCamelCase = Node(3) UpperCamelCase = Node(4) print(root_node.has_loop) # False UpperCamelCase = root_node.next_node print(root_node.has_loop) # True UpperCamelCase = Node(5) UpperCamelCase = Node(6) UpperCamelCase = Node(5) UpperCamelCase = Node(6) print(root_node.has_loop) # False UpperCamelCase = Node(1) print(root_node.has_loop) # False
334
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase = { '''configuration_vivit''': ['''VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VivitConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VivitImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''VivitModel''', '''VivitPreTrainedModel''', '''VivitForVideoClassification''', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
359
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE( __lowercase = 4 ) -> list[list[int]]: A: Tuple = abs(__lowercase ) or 4 return [[1 + x + y * row_size for x in range(__lowercase )] for y in range(__lowercase )] def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(transpose(__lowercase ) ) # OR.. transpose(reverse_column(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(reverse_column(__lowercase ) ) # OR.. reverse_column(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_column(transpose(__lowercase ) ) # OR.. transpose(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Union[str, Any] = [list(__lowercase ) for x in zip(*__lowercase )] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[int] = matrix[::-1] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[Any] = [x[::-1] for x in matrix] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> None: for i in matrix: print(*__lowercase ) if __name__ == "__main__": UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
334
0
'''simple docstring''' import re import string import numpy as np import datasets UpperCamelCase = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' UpperCamelCase = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' UpperCamelCase = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self : List[str] ) -> Any: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , reference_urls=[] , ) def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : List[str]=False , ) -> int: '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: A: Optional[int] = np.array([re.sub(SCREAMING_SNAKE_CASE_ , '''''' , SCREAMING_SNAKE_CASE_ ) for x in predictions] ) A: Dict = np.array([re.sub(SCREAMING_SNAKE_CASE_ , '''''' , SCREAMING_SNAKE_CASE_ ) for x in references] ) else: A: List[Any] = np.asarray(SCREAMING_SNAKE_CASE_ ) A: Any = np.asarray(SCREAMING_SNAKE_CASE_ ) if ignore_case: A: List[Any] = np.char.lower(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = np.char.lower(SCREAMING_SNAKE_CASE_ ) if ignore_punctuation: A: Tuple = string.punctuation.maketrans('''''' , '''''' , string.punctuation ) A: Dict = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) A: Any = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) if ignore_numbers: A: Optional[int] = string.digits.maketrans('''''' , '''''' , string.digits ) A: Optional[int] = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) A: Any = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = predictions == references return {"exact_match": np.mean(SCREAMING_SNAKE_CASE_ ) * 1_00}
360
'''simple docstring''' from __future__ import annotations import numpy as np def SCREAMING_SNAKE_CASE( __lowercase ) -> Dict: return np.maximum(0 , __lowercase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
334
0
from __future__ import annotations from math import pow, sqrt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> dict[str, float]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance == 0: return {"resistance": sqrt(pow(__lowercase , 2 ) - pow(__lowercase , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(__lowercase , 2 ) - pow(__lowercase , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(__lowercase , 2 ) + pow(__lowercase , 2 ) )} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
361
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_vision_text_dual_encoder''': ['''VisionTextDualEncoderConfig'''], '''processing_vision_text_dual_encoder''': ['''VisionTextDualEncoderProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VisionTextDualEncoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxVisionTextDualEncoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''TFVisionTextDualEncoderModel'''] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
362
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCamelCase = { '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecAudioConfig'''], '''configuration_data2vec_text''': [ '''DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecTextConfig''', '''Data2VecTextOnnxConfig''', ], '''configuration_data2vec_vision''': [ '''DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecVisionConfig''', '''Data2VecVisionOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecAudioForAudioFrameClassification''', '''Data2VecAudioForCTC''', '''Data2VecAudioForSequenceClassification''', '''Data2VecAudioForXVector''', '''Data2VecAudioModel''', '''Data2VecAudioPreTrainedModel''', ] UpperCamelCase = [ '''DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecTextForCausalLM''', '''Data2VecTextForMaskedLM''', '''Data2VecTextForMultipleChoice''', '''Data2VecTextForQuestionAnswering''', '''Data2VecTextForSequenceClassification''', '''Data2VecTextForTokenClassification''', '''Data2VecTextModel''', '''Data2VecTextPreTrainedModel''', ] UpperCamelCase = [ '''DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecVisionForImageClassification''', '''Data2VecVisionForMaskedImageModeling''', '''Data2VecVisionForSemanticSegmentation''', '''Data2VecVisionModel''', '''Data2VecVisionPreTrainedModel''', ] if is_tf_available(): UpperCamelCase = [ '''TFData2VecVisionForImageClassification''', '''TFData2VecVisionForSemanticSegmentation''', '''TFData2VecVisionModel''', '''TFData2VecVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
363
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : torch.FloatTensor class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE_ : int = 6_55_36 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : str = "fourier" , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , SCREAMING_SNAKE_CASE_ : Tuple[str] = "UNetMidBlock1D" , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : Tuple[int] = (32, 32, 64) , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : int = 8 , SCREAMING_SNAKE_CASE_ : int = 1 , SCREAMING_SNAKE_CASE_ : bool = False , ) -> Tuple: '''simple docstring''' super().__init__() A: Optional[Any] = sample_size # time if time_embedding_type == "fourier": A: Tuple = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=SCREAMING_SNAKE_CASE_ , log=SCREAMING_SNAKE_CASE_ , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ ) A: List[str] = 2 * block_out_channels[0] elif time_embedding_type == "positional": A: str = Timesteps( block_out_channels[0] , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ , downscale_freq_shift=SCREAMING_SNAKE_CASE_ ) A: Any = block_out_channels[0] if use_timestep_embedding: A: Optional[Any] = block_out_channels[0] * 4 A: List[Any] = TimestepEmbedding( in_channels=SCREAMING_SNAKE_CASE_ , time_embed_dim=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , out_dim=block_out_channels[0] , ) A: Optional[Any] = nn.ModuleList([] ) A: str = None A: str = nn.ModuleList([] ) A: Tuple = None # down A: Any = in_channels for i, down_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = output_channel A: List[Any] = block_out_channels[i] if i == 0: input_channel += extra_in_channels A: List[Any] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[int] = get_down_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(SCREAMING_SNAKE_CASE_ ) # mid A: Union[str, Any] = get_mid_block( SCREAMING_SNAKE_CASE_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=SCREAMING_SNAKE_CASE_ , add_downsample=SCREAMING_SNAKE_CASE_ , ) # up A: Optional[Any] = list(reversed(SCREAMING_SNAKE_CASE_ ) ) A: List[str] = reversed_block_out_channels[0] if out_block_type is None: A: int = out_channels else: A: Union[str, Any] = block_out_channels[0] for i, up_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: List[Any] = output_channel A: int = ( reversed_block_out_channels[i + 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 else final_upsample_channels ) A: Optional[int] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[Any] = get_up_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(SCREAMING_SNAKE_CASE_ ) A: Any = output_channel # out A: List[str] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) A: Optional[int] = get_out_block( out_block_type=SCREAMING_SNAKE_CASE_ , num_groups_out=SCREAMING_SNAKE_CASE_ , embed_dim=block_out_channels[0] , out_channels=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , fc_dim=block_out_channels[-1] // 4 , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : torch.FloatTensor , SCREAMING_SNAKE_CASE_ : Union[torch.Tensor, float, int] , SCREAMING_SNAKE_CASE_ : bool = True , ) -> Union[UNetaDOutput, Tuple]: '''simple docstring''' A: Any = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(SCREAMING_SNAKE_CASE_ ) and len(timesteps.shape ) == 0: A: List[str] = timesteps[None].to(sample.device ) A: int = self.time_proj(SCREAMING_SNAKE_CASE_ ) if self.config.use_timestep_embedding: A: List[Any] = self.time_mlp(SCREAMING_SNAKE_CASE_ ) else: A: str = timestep_embed[..., None] A: Union[str, Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) A: Tuple = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down A: List[str] = () for downsample_block in self.down_blocks: A , A: Optional[int] = downsample_block(hidden_states=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: A: Dict = self.mid_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): A: List[Any] = down_block_res_samples[-1:] A: List[str] = down_block_res_samples[:-1] A: Optional[int] = upsample_block(SCREAMING_SNAKE_CASE_ , res_hidden_states_tuple=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) # 5. post-process if self.out_block: A: Any = self.out_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' UpperCamelCase = tuple[float, float, float] UpperCamelCase = tuple[float, float, float] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Vectorad: A: Optional[Any] = end_pointa[0] - end_pointa[0] A: Any = end_pointa[1] - end_pointa[1] A: str = end_pointa[2] - end_pointa[2] return (x, y, z) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Vectorad: A: Union[str, Any] = ab[1] * ac[2] - ab[2] * ac[1] # *i A: Any = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j A: Tuple = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> bool: return tuple(round(__lowercase , __lowercase ) for x in vector ) == (0, 0, 0) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = 1_0 ) -> bool: A: Any = create_vector(__lowercase , __lowercase ) A: Any = create_vector(__lowercase , __lowercase ) return is_zero_vector(get_ad_vectors_cross(__lowercase , __lowercase ) , __lowercase )
364
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , *SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Dict ) -> None: '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class lowerCAmelCase_ ( UpperCAmelCase_ ): UpperCamelCase_ : Any = (DPMSolverSinglestepScheduler,) UpperCamelCase_ : Optional[int] = (("""num_inference_steps""", 25),) def _snake_case ( self : Optional[Any] , **SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> List[Any]: '''simple docstring''' A: List[Any] = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, '''prediction_type''': '''epsilon''', '''thresholding''': False, '''sample_max_value''': 1.0, '''algorithm_type''': '''dpmsolver++''', '''solver_type''': '''midpoint''', '''lambda_min_clipped''': -float('''inf''' ), '''variance_type''': None, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : Tuple=0 , **SCREAMING_SNAKE_CASE_ : Any ) -> int: '''simple docstring''' A: str = dict(self.forward_default_kwargs ) A: Optional[Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = self.dummy_sample A: Any = 0.1 * sample A: Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A: List[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) A: Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals A: List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE_ ) A: str = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals A: Any = dummy_past_residuals[: new_scheduler.config.solver_order] A: str = sample, sample for t in range(SCREAMING_SNAKE_CASE_ , time_step + scheduler.config.solver_order + 1 ): A: Union[str, Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Dict = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _snake_case ( self : str ) -> Dict: '''simple docstring''' pass def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Dict=0 , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' A: List[Any] = dict(self.forward_default_kwargs ) A: int = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE_ ) A: Tuple = self.dummy_sample A: int = 0.1 * sample A: List[str] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A: int = self.get_scheduler_config() A: List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals (must be after setting timesteps) A: Union[str, Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE_ ) A: Tuple = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residual (must be after setting timesteps) A: List[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A: Union[str, Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Dict = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any]=None , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[Any]: '''simple docstring''' if scheduler is None: A: str = self.scheduler_classes[0] A: Union[str, Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) A: Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) A: Tuple = self.scheduler_classes[0] A: int = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) A: List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = 10 A: Union[str, Any] = self.dummy_model() A: int = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): A: Dict = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Tuple = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def _snake_case ( self : Tuple ) -> int: '''simple docstring''' A: List[str] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) A: Tuple = 50 A: List[str] = self.dummy_model() A: str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): A: Dict = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample A: Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.2574 ) < 1E-3 def _snake_case ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' for timesteps in [25, 50, 1_00, 9_99, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' A: str = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) A: str = self.full_loop(scheduler=SCREAMING_SNAKE_CASE_ ) A: int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.2791 ) < 1E-3 A: int = DEISMultistepScheduler.from_config(scheduler.config ) A: Optional[int] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A: Dict = UniPCMultistepScheduler.from_config(scheduler.config ) A: Tuple = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A: List[Any] = self.full_loop(scheduler=SCREAMING_SNAKE_CASE_ ) A: str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.2791 ) < 1E-3 def _snake_case ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , algorithm_type='''dpmsolver++''' , solver_order=SCREAMING_SNAKE_CASE_ , solver_type=SCREAMING_SNAKE_CASE_ , ) def _snake_case ( self : Dict ) -> Optional[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=SCREAMING_SNAKE_CASE_ , solver_type=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , algorithm_type=SCREAMING_SNAKE_CASE_ , ) A: List[Any] = self.full_loop( solver_order=SCREAMING_SNAKE_CASE_ , solver_type=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , algorithm_type=SCREAMING_SNAKE_CASE_ , ) assert not torch.isnan(SCREAMING_SNAKE_CASE_ ).any(), "Samples have nan numbers" def _snake_case ( self : Dict ) -> Any: '''simple docstring''' self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE_ ) self.check_over_configs(lower_order_final=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Any ) -> List[Any]: '''simple docstring''' self.check_over_configs(lambda_min_clipped=-float('''inf''' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE_ ) self.check_over_configs(variance_type='''learned_range''' ) def _snake_case ( self : int ) -> Optional[int]: '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]: self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE_ , time_step=0 ) def _snake_case ( self : Optional[Any] ) -> List[str]: '''simple docstring''' A: Optional[Any] = self.full_loop() A: int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.2791 ) < 1E-3 def _snake_case ( self : Tuple ) -> Any: '''simple docstring''' A: Dict = self.full_loop(use_karras_sigmas=SCREAMING_SNAKE_CASE_ ) A: str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.2248 ) < 1E-3 def _snake_case ( self : Optional[Any] ) -> str: '''simple docstring''' A: str = self.full_loop(prediction_type='''v_prediction''' ) A: Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.1453 ) < 1E-3 def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' A: List[str] = self.full_loop(prediction_type='''v_prediction''' , use_karras_sigmas=SCREAMING_SNAKE_CASE_ ) A: List[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_mean.item() - 0.0649 ) < 1E-3 def _snake_case ( self : Tuple ) -> int: '''simple docstring''' A: Any = self.scheduler_classes[0] A: Optional[Any] = self.get_scheduler_config(thresholding=SCREAMING_SNAKE_CASE_ , dynamic_thresholding_ratio=0 ) A: Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = 10 A: Tuple = self.dummy_model() A: Tuple = self.dummy_sample_deter.half() scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): A: Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample assert sample.dtype == torch.floataa
365
'''simple docstring''' from collections import deque class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> None: '''simple docstring''' A: Union[str, Any] = process_name # process name A: List[str] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time A: Dict = arrival_time A: Optional[Any] = burst_time # remaining burst time A: Any = 0 # total time of the process wait in ready queue A: Any = 0 # time from arrival time to completion time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int , ) -> None: '''simple docstring''' A: Dict = number_of_queues # time slice of queues that round robin algorithm applied A: int = time_slices # unfinished process is in this ready_queue A: Tuple = queue # current time A: int = current_time # finished process is in this sequence queue A: deque[Process] = deque() def _snake_case ( self : List[Any] ) -> list[str]: '''simple docstring''' A: str = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Optional[int] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Any = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: List[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> list[int]: '''simple docstring''' return [q.burst_time for q in queue] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Process ) -> int: '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> deque[Process]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE_ ) != 0: A: Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 A: Any = 0 # set the process's turnaround time because it is finished A: int = self.current_time - cp.arrival_time # set the completion time A: List[str] = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int ) -> tuple[deque[Process], deque[Process]]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE_ ) ): A: Dict = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time A: Optional[Any] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished A: int = 0 # set the finish time A: Union[str, Any] = self.current_time # update the process' turnaround time because it is finished A: Tuple = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _snake_case ( self : Optional[Any] ) -> deque[Process]: '''simple docstring''' for i in range(self.number_of_queues - 1 ): A , A: Optional[Any] = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])}) UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) UpperCamelCase = MLFQ(number_of_queues, time_slices, queue, 0) UpperCamelCase = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print completion times of processes(P1, P2, P3, P4) print( f'completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print sequence of finished processes print( f'sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}' )
334
0
'''simple docstring''' import math import sys def SCREAMING_SNAKE_CASE( __lowercase ) -> int: if number != int(__lowercase ): raise ValueError('''the value of input must be a natural number''' ) if number < 0: raise ValueError('''the value of input must not be a negative number''' ) if number == 0: return 1 A: int = [-1] * (number + 1) A: List[str] = 0 for i in range(1 , number + 1 ): A: Tuple = sys.maxsize A: Optional[int] = int(math.sqrt(__lowercase ) ) for j in range(1 , root + 1 ): A: str = 1 + answers[i - (j**2)] A: Dict = min(__lowercase , __lowercase ) A: str = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
366
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : List[nn.Module] = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : list = field(default_factory=UpperCAmelCase_ ) def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tensor , SCREAMING_SNAKE_CASE_ : Tensor ) -> int: '''simple docstring''' A: List[str] = len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE_ , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE_ ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tensor ) -> Dict: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE_ ) [x.remove() for x in self.handles] return self @property def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' return list(filter(lambda SCREAMING_SNAKE_CASE_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : nn.Module UpperCamelCase_ : int = 0 UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) def __call__( self : Any , SCREAMING_SNAKE_CASE_ : Tensor ) -> Optional[Any]: '''simple docstring''' A: Dict = Tracker(self.dest )(SCREAMING_SNAKE_CASE_ ).parametrized A: Tuple = Tracker(self.src )(SCREAMING_SNAKE_CASE_ ).parametrized A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.src_skip , SCREAMING_SNAKE_CASE_ ) ) A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.dest_skip , SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise Exception( f"""Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE_ )} operations while""" f""" destination module has {len(SCREAMING_SNAKE_CASE_ )}.""" ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = True ) -> Any: print(F"""Converting {name}...""" ) with torch.no_grad(): A: Union[str, Any] = timm.create_model(__lowercase , pretrained=__lowercase ).eval() A: List[str] = ResNetForImageClassification(__lowercase ).eval() A: int = ModuleTransfer(src=__lowercase , dest=__lowercase ) A: List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(__lowercase ) assert torch.allclose(from_model(__lowercase ) , our_model(__lowercase ).logits ), "The model logits don't match the original one." A: str = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(__lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=__lowercase , ) # we can use the convnext one A: Any = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=__lowercase , ) print(F"""Pushed {checkpoint_name}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = None , __lowercase = True ) -> List[Any]: A: Union[str, Any] = '''imagenet-1k-id2label.json''' A: Union[str, Any] = 1_0_0_0 A: Optional[int] = (1, num_labels) A: Dict = '''huggingface/label-files''' A: Any = num_labels A: Union[str, Any] = json.load(open(hf_hub_download(__lowercase , __lowercase , repo_type='''dataset''' ) , '''r''' ) ) A: Optional[int] = {int(__lowercase ): v for k, v in idalabel.items()} A: Optional[int] = idalabel A: List[str] = {v: k for k, v in idalabel.items()} A: str = partial(__lowercase , num_labels=__lowercase , idalabel=__lowercase , labelaid=__lowercase ) A: Optional[Any] = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(__lowercase , names_to_config[model_name] , __lowercase , __lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowercase , __lowercase , __lowercase , __lowercase ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase = { '''configuration_upernet''': ['''UperNetConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''UperNetForSemanticSegmentation''', '''UperNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
367
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str | Literal[False]: A: List[str] = list(__lowercase ) A: Optional[Any] = list(__lowercase ) A: int = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count += 1 A: Optional[Any] = '''_''' if count > 1: return False else: return "".join(__lowercase ) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[str]: A: Any = [] while True: A: Dict = ['''$'''] * len(__lowercase ) A: Union[str, Any] = [] for i in range(len(__lowercase ) ): for j in range(i + 1 , len(__lowercase ) ): A: Any = compare_string(binary[i] , binary[j] ) if k is False: A: Any = '''*''' A: List[Any] = '''*''' temp.append('''X''' ) for i in range(len(__lowercase ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__lowercase ) == 0: return pi A: List[Any] = list(set(__lowercase ) ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: Optional[int] = [] for minterm in minterms: A: Optional[int] = '''''' for _ in range(__lowercase ): A: List[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(__lowercase ) return temp def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> bool: A: Union[str, Any] = list(__lowercase ) A: Union[str, Any] = list(__lowercase ) A: Optional[int] = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: List[Any] = [] A: Dict = [0] * len(__lowercase ) for i in range(len(chart[0] ) ): A: List[str] = 0 A: str = -1 for j in range(len(__lowercase ) ): if chart[j][i] == 1: count += 1 A: Any = j if count == 1: A: Any = 1 for i in range(len(__lowercase ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(__lowercase ) ): A: Optional[int] = 0 temp.append(prime_implicants[i] ) while True: A: Dict = 0 A: Optional[int] = -1 A: Dict = 0 for i in range(len(__lowercase ) ): A: str = chart[i].count(1 ) if count_n > max_n: A: Tuple = count_n A: Optional[Any] = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(__lowercase ) ): A: Any = 0 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[int]]: A: str = [[0 for x in range(len(__lowercase ) )] for x in range(len(__lowercase ) )] for i in range(len(__lowercase ) ): A: Tuple = prime_implicants[i].count('''_''' ) for j in range(len(__lowercase ) ): if is_for_table(prime_implicants[i] , binary[j] , __lowercase ): A: Optional[Any] = 1 return chart def SCREAMING_SNAKE_CASE( ) -> None: A: int = int(input('''Enter the no. of variables\n''' ) ) A: Optional[int] = [ float(__lowercase ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] A: List[str] = decimal_to_binary(__lowercase , __lowercase ) A: str = check(__lowercase ) print('''Prime Implicants are:''' ) print(__lowercase ) A: List[Any] = prime_implicant_chart(__lowercase , __lowercase ) A: Any = selection(__lowercase , __lowercase ) print('''Essential Prime Implicants are:''' ) print(__lowercase ) if __name__ == "__main__": import doctest doctest.testmod() main()
334
0
'''simple docstring''' import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : List[Any] = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any]="</s>" , SCREAMING_SNAKE_CASE_ : Any="<unk>" , SCREAMING_SNAKE_CASE_ : int="<pad>" , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_25 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> None: '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: A: List[Any] = [f"""<extra_id_{i}>""" for i in range(SCREAMING_SNAKE_CASE_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens A: int = len(set(filter(lambda SCREAMING_SNAKE_CASE_ : bool('''extra_id''' in str(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ''' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the''' ''' extra_ids tokens''' ) A: Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token A: List[str] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token A: Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token super().__init__( eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , extra_ids=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = extra_ids A: Tuple = 2**8 # utf is 8 bits # define special tokens dict A: Dict[int, str] = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } A: Union[str, Any] = len(self.special_tokens_encoder ) A: Dict = len(SCREAMING_SNAKE_CASE_ ) for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = self.vocab_size + i - n A: Dict[str, int] = {v: k for k, v in self.special_tokens_encoder.items()} @property def _snake_case ( self : List[str] ) -> int: '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE_ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[int] ) -> List[int]: '''simple docstring''' if len(SCREAMING_SNAKE_CASE_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: str = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: List[str] = self._add_eos_if_not_present(SCREAMING_SNAKE_CASE_ ) if token_ids_a is None: return token_ids_a else: A: int = self._add_eos_if_not_present(SCREAMING_SNAKE_CASE_ ) return token_ids_a + token_ids_a def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str ) -> List[str]: '''simple docstring''' A: Tuple = [chr(SCREAMING_SNAKE_CASE_ ) for i in text.encode('''utf-8''' )] return tokens def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : int ) -> List[str]: '''simple docstring''' if token in self.special_tokens_encoder: A: str = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: A: Any = self.added_tokens_encoder[token] elif len(SCREAMING_SNAKE_CASE_ ) != 1: A: List[Any] = self.unk_token_id else: A: Any = ord(SCREAMING_SNAKE_CASE_ ) + self._num_special_tokens return token_id def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' if index in self.special_tokens_decoder: A: int = self.special_tokens_decoder[index] else: A: Union[str, Any] = chr(index - self._num_special_tokens ) return token def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> int: '''simple docstring''' A: Tuple = b'''''' for token in tokens: if token in self.special_tokens_decoder: A: Optional[int] = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.added_tokens_decoder: A: Union[str, Any] = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.special_tokens_encoder: A: Optional[Any] = token.encode('''utf-8''' ) elif token in self.added_tokens_encoder: A: int = token.encode('''utf-8''' ) else: A: List[Any] = bytes([ord(SCREAMING_SNAKE_CASE_ )] ) bstring += tok_string A: Tuple = bstring.decode('''utf-8''' , errors='''ignore''' ) return string def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' return ()
368
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> Tuple: A: Tuple = len(__lowercase ) for i in range(length - 1 ): A: Dict = i for k in range(i + 1 , __lowercase ): if collection[k] < collection[least]: A: List[str] = k if least != i: A , A: Tuple = (collection[i], collection[least]) return collection if __name__ == "__main__": UpperCamelCase = input('''Enter numbers separated by a comma:\n''').strip() UpperCamelCase = [int(item) for item in user_input.split(''',''')] print(selection_sort(unsorted))
334
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=False ) -> int: A: Tuple = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('''cls_token''', '''vit.embeddings.cls_token'''), ('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" A: int = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase=False ) -> Dict: for i in range(config.num_hidden_layers ): if base_model: A: str = '''''' else: A: Union[str, Any] = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A: Tuple = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) A: Any = state_dict.pop(F"""blocks.{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: List[str] = in_proj_bias[: config.hidden_size] A: List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A: Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A: Union[str, Any] = in_proj_weight[ -config.hidden_size :, : ] A: List[Any] = in_proj_bias[-config.hidden_size :] def SCREAMING_SNAKE_CASE( __lowercase ) -> List[Any]: A: Tuple = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(__lowercase , __lowercase ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Dict: A: int = dct.pop(__lowercase ) A: List[str] = val def SCREAMING_SNAKE_CASE( ) -> str: A: Union[str, Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A: List[str] = Image.open(requests.get(__lowercase , stream=__lowercase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Tuple: A: Optional[int] = ViTConfig() A: Union[str, Any] = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": A: Optional[int] = True A: Dict = int(vit_name[-1_2:-1_0] ) A: int = int(vit_name[-9:-6] ) else: A: int = 1_0_0_0 A: Union[str, Any] = '''huggingface/label-files''' A: List[str] = '''imagenet-1k-id2label.json''' A: Optional[Any] = json.load(open(hf_hub_download(__lowercase , __lowercase , repo_type='''dataset''' ) , '''r''' ) ) A: Any = {int(__lowercase ): v for k, v in idalabel.items()} A: Union[str, Any] = idalabel A: str = {v: k for k, v in idalabel.items()} A: str = int(vit_name[-6:-4] ) A: Optional[int] = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith('''tiny''' ): A: Any = 1_9_2 A: List[Any] = 7_6_8 A: List[str] = 1_2 A: Union[str, Any] = 3 elif vit_name[9:].startswith('''small''' ): A: str = 3_8_4 A: int = 1_5_3_6 A: int = 1_2 A: Any = 6 else: pass else: if vit_name[4:].startswith('''small''' ): A: Any = 7_6_8 A: List[Any] = 2_3_0_4 A: Any = 8 A: Tuple = 8 elif vit_name[4:].startswith('''base''' ): pass elif vit_name[4:].startswith('''large''' ): A: List[Any] = 1_0_2_4 A: Any = 4_0_9_6 A: Optional[int] = 2_4 A: Any = 1_6 elif vit_name[4:].startswith('''huge''' ): A: List[str] = 1_2_8_0 A: str = 5_1_2_0 A: Optional[int] = 3_2 A: int = 1_6 # load original model from timm A: List[str] = timm.create_model(__lowercase , pretrained=__lowercase ) timm_model.eval() # load state_dict of original model, remove and rename some keys A: Any = timm_model.state_dict() if base_model: remove_classification_head_(__lowercase ) A: Optional[Any] = create_rename_keys(__lowercase , __lowercase ) for src, dest in rename_keys: rename_key(__lowercase , __lowercase , __lowercase ) read_in_q_k_v(__lowercase , __lowercase , __lowercase ) # load HuggingFace model if vit_name[-5:] == "in21k": A: Optional[int] = ViTModel(__lowercase ).eval() else: A: Any = ViTForImageClassification(__lowercase ).eval() model.load_state_dict(__lowercase ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: A: int = DeiTImageProcessor(size=config.image_size ) else: A: List[Any] = ViTImageProcessor(size=config.image_size ) A: str = image_processor(images=prepare_img() , return_tensors='''pt''' ) A: Optional[int] = encoding['''pixel_values'''] A: Dict = model(__lowercase ) if base_model: A: Dict = timm_model.forward_features(__lowercase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__lowercase , outputs.pooler_output , atol=1E-3 ) else: A: Tuple = timm_model(__lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__lowercase , outputs.logits , atol=1E-3 ) Path(__lowercase ).mkdir(exist_ok=__lowercase ) print(F"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__lowercase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__lowercase ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--vit_name''', default='''vit_base_patch16_224''', type=str, help='''Name of the ViT timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) UpperCamelCase = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
369
'''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> int: '''simple docstring''' A: Tuple = None A: Dict = None A: Optional[int] = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: str = len(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = None def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ) -> str: '''simple docstring''' if sources is int: A: Union[str, Any] = [sources] if sinks is int: A: Tuple = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return A: List[str] = sources[0] A: Optional[int] = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: A: Any = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A: Dict = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A: Optional[Any] = max_input_flow A: Optional[Any] = 0 A: str = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A: Optional[Any] = max_input_flow A: str = size - 1 def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple: '''simple docstring''' A: Optional[Any] = algorithm(self ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: '''simple docstring''' A: str = flow_network A: List[str] = flow_network.verticesCount A: Dict = flow_network.sourceIndex A: Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A: str = flow_network.graph A: str = False def _snake_case ( self : int ) -> Union[str, Any]: '''simple docstring''' if not self.executed: self._algorithm() A: str = True def _snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' pass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result A: Any = -1 def _snake_case ( self : List[str] ) -> Optional[Any]: '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [[0] * self.verticies_count for i in range(self.verticies_count )] A: Any = [0] * self.verticies_count A: Optional[Any] = [0] * self.verticies_count def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' A: Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A: str = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A: Dict = 0 while i < len(SCREAMING_SNAKE_CASE_ ): A: Any = vertices_list[i] A: str = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) A: Tuple = 0 else: i += 1 A: Tuple = sum(self.preflow[self.source_index] ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: '''simple docstring''' A: Optional[int] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str ) -> int: '''simple docstring''' A: Optional[Any] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A: List[Any] = self.heights[to_index] if min_height is not None: A: int = min_height + 1 if __name__ == "__main__": UpperCamelCase = [0] UpperCamelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCamelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCamelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCamelCase = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
334
0
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] , 1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
370
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase ) -> int: A: Any = len(__lowercase ), len(grid[0] ) if ( min(__lowercase , __lowercase ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) A: List[Any] = 0 count += depth_first_search(__lowercase , row + 1 , __lowercase , __lowercase ) count += depth_first_search(__lowercase , row - 1 , __lowercase , __lowercase ) count += depth_first_search(__lowercase , __lowercase , col + 1 , __lowercase ) count += depth_first_search(__lowercase , __lowercase , col - 1 , __lowercase ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
371
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = DebertaTokenizer UpperCamelCase_ : List[str] = True UpperCamelCase_ : int = DebertaTokenizerFast def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A: Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] A: int = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A: Union[str, Any] = {'''unk_token''': '''[UNK]'''} A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: str = 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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : int , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = '''lower newer''' A: str = '''lower newer''' return input_text, output_text def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: str = self.get_tokenizer() A: Any = '''lower newer''' A: Dict = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] A: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokens + [tokenizer.unk_token] A: int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' A: str = self.get_tokenizer() A: List[str] = tokenizer('''Hello''' , '''World''' ) A: Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Tuple ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) A: int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _snake_case ( self : Tuple ) -> Dict: '''simple docstring''' A: int = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: A: List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Dict = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] A: Dict = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: Any = [tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) for seq in encoding['''input_ids''']] # fmt: off A: Any = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on A: Optional[int] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , SCREAMING_SNAKE_CASE_ ) for expected, decoded in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', } UpperCamelCase = { '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''}, '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''}, } UpperCamelCase = { '''ctrl''': 256, } UpperCamelCase = { '''Pregnancy''': 168629, '''Christianity''': 7675, '''Explain''': 106423, '''Fitness''': 63440, '''Saving''': 63163, '''Ask''': 27171, '''Ass''': 95985, '''Joke''': 163509, '''Questions''': 45622, '''Thoughts''': 49605, '''Retail''': 52342, '''Feminism''': 164338, '''Writing''': 11992, '''Atheism''': 192263, '''Netflix''': 48616, '''Computing''': 39639, '''Opinion''': 43213, '''Alone''': 44967, '''Funny''': 58917, '''Gaming''': 40358, '''Human''': 4088, '''India''': 1331, '''Joker''': 77138, '''Diet''': 36206, '''Legal''': 11859, '''Norman''': 4939, '''Tip''': 72689, '''Weight''': 52343, '''Movies''': 46273, '''Running''': 23425, '''Science''': 2090, '''Horror''': 37793, '''Confession''': 60572, '''Finance''': 12250, '''Politics''': 16360, '''Scary''': 191985, '''Support''': 12654, '''Technologies''': 32516, '''Teenage''': 66160, '''Event''': 32769, '''Learned''': 67460, '''Notion''': 182770, '''Wikipedia''': 37583, '''Books''': 6665, '''Extract''': 76050, '''Confessions''': 102701, '''Conspiracy''': 75932, '''Links''': 63674, '''Narcissus''': 150425, '''Relationship''': 54766, '''Relationships''': 134796, '''Reviews''': 41671, '''News''': 4256, '''Translation''': 26820, '''multilingual''': 128406, } def SCREAMING_SNAKE_CASE( __lowercase ) -> Union[str, Any]: A: Dict = set() A: Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) A: Optional[int] = char A: Union[str, Any] = set(__lowercase ) return pairs class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : str = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Optional[Any] = CONTROL_CODES def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any="<unk>" , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> Dict: '''simple docstring''' super().__init__(unk_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , encoding='''utf-8''' ) as vocab_handle: A: int = json.load(SCREAMING_SNAKE_CASE_ ) A: str = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE_ , encoding='''utf-8''' ) as merges_handle: A: List[Any] = merges_handle.read().split('''\n''' )[1:-1] A: Any = [tuple(merge.split() ) for merge in merges] A: Optional[int] = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Any = {} @property def _snake_case ( self : int ) -> Optional[Any]: '''simple docstring''' return len(self.encoder ) def _snake_case ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Any ) -> Tuple: '''simple docstring''' if token in self.cache: return self.cache[token] A: Optional[Any] = tuple(SCREAMING_SNAKE_CASE_ ) A: str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) A: int = get_pairs(SCREAMING_SNAKE_CASE_ ) if not pairs: return token while True: A: Union[str, Any] = min(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break A: Any = bigram A: Optional[int] = [] A: Dict = 0 while i < len(SCREAMING_SNAKE_CASE_ ): try: A: Optional[Any] = word.index(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) A: List[Any] = j if word[i] == first and i < len(SCREAMING_SNAKE_CASE_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 A: Optional[int] = tuple(SCREAMING_SNAKE_CASE_ ) A: List[Any] = new_word if len(SCREAMING_SNAKE_CASE_ ) == 1: break else: A: Tuple = get_pairs(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = '''@@ '''.join(SCREAMING_SNAKE_CASE_ ) A: Any = word[:-4] A: Tuple = word return word def _snake_case ( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' A: int = [] A: Any = re.findall(R'''\S+\n?''' , SCREAMING_SNAKE_CASE_ ) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE_ ).split(''' ''' ) ) ) return split_tokens def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> List[Any]: '''simple docstring''' return self.encoder.get(SCREAMING_SNAKE_CASE_ , self.encoder.get(self.unk_token ) ) def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str ) -> Dict: '''simple docstring''' return self.decoder.get(SCREAMING_SNAKE_CASE_ , self.unk_token ) def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[int]: '''simple docstring''' A: Tuple = ''' '''.join(SCREAMING_SNAKE_CASE_ ).replace('''@@ ''' , '''''' ).strip() return out_string def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return A: Optional[Any] = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) A: Any = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + '''\n''' ) A: Optional[int] = 0 with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) A: Optional[Any] = token_index writer.write(''' '''.join(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
350
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] , 1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
334
0
def SCREAMING_SNAKE_CASE( __lowercase ) -> list: if len(__lowercase ) <= 1: return [tuple(__lowercase )] A: Any = [] def generate(__lowercase , __lowercase ): A: Union[str, Any] = [0] * n res.append(tuple(__lowercase ) ) A: Optional[int] = 0 while i < n: if c[i] < i: if i % 2 == 0: A: Union[str, Any] = arr[i], arr[0] else: A: List[str] = arr[i], arr[c[i]] res.append(tuple(__lowercase ) ) c[i] += 1 A: Dict = 0 else: A: str = 0 i += 1 generate(len(__lowercase ) , __lowercase ) return res if __name__ == "__main__": UpperCamelCase = input('''Enter numbers separated by a comma:\n''').strip() UpperCamelCase = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
351
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } UpperCamelCase = { '''camembert-base''': 512, } UpperCamelCase = '''▁''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : str = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : int = CamembertTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : str="<s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE_ : List[Any]="</s>" , SCREAMING_SNAKE_CASE_ : int="<s>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<unk>" , SCREAMING_SNAKE_CASE_ : str="<pad>" , SCREAMING_SNAKE_CASE_ : List[str]="<mask>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , **SCREAMING_SNAKE_CASE_ : Any , ) -> Any: '''simple docstring''' A: Tuple = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Any = vocab_file A: Any = False if not self.vocab_file else True def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''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: List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: List[str] = [self.sep_token_id] A: Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return A: Dict = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
334
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''', } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Any = """blip_2_vision_model""" def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[int]=14_08 , SCREAMING_SNAKE_CASE_ : Optional[Any]=61_44 , SCREAMING_SNAKE_CASE_ : str=39 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE_ : Dict=2_24 , SCREAMING_SNAKE_CASE_ : Optional[int]=14 , SCREAMING_SNAKE_CASE_ : Tuple="gelu" , SCREAMING_SNAKE_CASE_ : Any=0.0_0001 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.0 , SCREAMING_SNAKE_CASE_ : Tuple=1E-10 , SCREAMING_SNAKE_CASE_ : List[Any]=True , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> Tuple: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) A = hidden_size A = intermediate_size A = num_hidden_layers A = num_attention_heads A = patch_size A = image_size A = initializer_range A = attention_dropout A = layer_norm_eps A = hidden_act A = qkv_bias @classmethod def _snake_case ( cls : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE_ : Any ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) A = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": A = 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(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Dict = """blip_2_qformer""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3_05_22 , SCREAMING_SNAKE_CASE_ : str=7_68 , SCREAMING_SNAKE_CASE_ : Tuple=12 , SCREAMING_SNAKE_CASE_ : Dict=12 , SCREAMING_SNAKE_CASE_ : Optional[Any]=30_72 , SCREAMING_SNAKE_CASE_ : Tuple="gelu" , SCREAMING_SNAKE_CASE_ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE_ : List[str]=0.1 , SCREAMING_SNAKE_CASE_ : Any=5_12 , SCREAMING_SNAKE_CASE_ : Dict=0.02 , SCREAMING_SNAKE_CASE_ : Any=1E-12 , SCREAMING_SNAKE_CASE_ : str=0 , SCREAMING_SNAKE_CASE_ : Optional[Any]="absolute" , SCREAMING_SNAKE_CASE_ : List[Any]=2 , SCREAMING_SNAKE_CASE_ : Optional[int]=14_08 , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = initializer_range A = layer_norm_eps A = position_embedding_type A = cross_attention_frequency A = encoder_hidden_size @classmethod def _snake_case ( cls : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE_ : str ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) A = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": A = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : str = """blip-2""" UpperCamelCase_ : List[str] = True def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , SCREAMING_SNAKE_CASE_ : str=None , SCREAMING_SNAKE_CASE_ : Any=32 , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) if vision_config is None: A = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: A = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: A = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) A = BlipaVisionConfig(**SCREAMING_SNAKE_CASE_ ) A = BlipaQFormerConfig(**SCREAMING_SNAKE_CASE_ ) A = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' A = CONFIG_MAPPING[text_model_type](**SCREAMING_SNAKE_CASE_ ) A = self.text_config.tie_word_embeddings A = self.text_config.is_encoder_decoder A = num_query_tokens A = self.vision_config.hidden_size A = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES A = 1.0 A = 0.02 @classmethod def _snake_case ( cls : Any , SCREAMING_SNAKE_CASE_ : BlipaVisionConfig , SCREAMING_SNAKE_CASE_ : BlipaQFormerConfig , SCREAMING_SNAKE_CASE_ : PretrainedConfig , **SCREAMING_SNAKE_CASE_ : List[Any] , ) -> List[str]: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **SCREAMING_SNAKE_CASE_ , ) def _snake_case ( self : List[Any] ) -> Optional[int]: '''simple docstring''' A = copy.deepcopy(self.__dict__ ) A = self.vision_config.to_dict() A = self.qformer_config.to_dict() A = self.text_config.to_dict() A = self.__class__.model_type return output
352
'''simple docstring''' import os from distutils.util import strtobool def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[Any]: for e in env_keys: A: Dict = int(os.environ.get(__lowercase , -1 ) ) if val >= 0: return val return default def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=False ) -> List[str]: A: str = os.environ.get(__lowercase , str(__lowercase ) ) return strtobool(__lowercase ) == 1 # As its name indicates `strtobool` actually returns an int... def SCREAMING_SNAKE_CASE( __lowercase , __lowercase="no" ) -> str: A: Optional[int] = os.environ.get(__lowercase , str(__lowercase ) ) return value
334
0
'''simple docstring''' import requests from bsa import BeautifulSoup def SCREAMING_SNAKE_CASE( __lowercase = "AAPL" ) -> str: A: Any = F"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" A: int = BeautifulSoup(requests.get(__lowercase ).text , '''html.parser''' ) A: Any = '''My(6px) Pos(r) smartphone_Mt(6px)''' return soup.find('''div''' , class_=class_ ).find('''span''' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'Current {symbol:<4} stock price is {stock_price(symbol):>8}')
353
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() UpperCamelCase = logging.get_logger('''transformers.models.encodec''') UpperCamelCase = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } UpperCamelCase = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } UpperCamelCase = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } UpperCamelCase = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } UpperCamelCase = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } UpperCamelCase = [] UpperCamelCase = [] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: for attribute in key.split('''.''' ): A: Union[str, Any] = getattr(__lowercase , __lowercase ) if weight_type is not None: A: Tuple = getattr(__lowercase , __lowercase ).shape else: A: str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": A: Dict = value elif weight_type == "weight_g": A: Tuple = value elif weight_type == "weight_v": A: Any = value elif weight_type == "bias": A: str = value elif weight_type == "running_mean": A: List[Any] = value elif weight_type == "running_var": A: Dict = value elif weight_type == "num_batches_tracked": A: List[str] = value elif weight_type == "weight_ih_l0": A: Dict = value elif weight_type == "weight_hh_l0": A: Optional[int] = value elif weight_type == "bias_ih_l0": A: List[Any] = value elif weight_type == "bias_hh_l0": A: str = value elif weight_type == "weight_ih_l1": A: Optional[int] = value elif weight_type == "weight_hh_l1": A: int = value elif weight_type == "bias_ih_l1": A: Optional[Any] = value elif weight_type == "bias_hh_l1": A: str = value else: A: Optional[int] = value logger.info(F"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Optional[Any]: for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: A , A: Any = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Tuple: A: Any = [] if model_name == "encodec_24khz" or "encodec_32khz": A: List[str] = MAPPING_24K elif model_name == "encodec_48khz": A: List[Any] = MAPPING_48K else: raise ValueError(F"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(__lowercase , __lowercase ): logger.info(F"""{name} was ignored""" ) continue A: Optional[int] = False for key, mapped_key in MAPPING.items(): if "*" in key: A , A: Optional[int] = key.split('''.*.''' ) if prefix in name and suffix in name: A: str = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('''embed''' ) and name.endswith('''embed_avg''' ): continue A: Optional[Any] = True if "*" in mapped_key: A: Any = name.split(__lowercase )[0].split('''.''' )[-2] A: Tuple = mapped_key.replace('''*''' , __lowercase ) if "weight_g" in name: A: str = '''weight_g''' elif "weight_v" in name: A: List[Any] = '''weight_v''' elif "weight_ih_l0" in name: A: Dict = '''weight_ih_l0''' elif "weight_hh_l0" in name: A: int = '''weight_hh_l0''' elif "bias_ih_l0" in name: A: Union[str, Any] = '''bias_ih_l0''' elif "bias_hh_l0" in name: A: Tuple = '''bias_hh_l0''' elif "weight_ih_l1" in name: A: int = '''weight_ih_l1''' elif "weight_hh_l1" in name: A: Optional[Any] = '''weight_hh_l1''' elif "bias_ih_l1" in name: A: Dict = '''bias_ih_l1''' elif "bias_hh_l1" in name: A: str = '''bias_hh_l1''' elif "bias" in name: A: Union[str, Any] = '''bias''' elif "weight" in name: A: Dict = '''weight''' elif "running_mean" in name: A: Tuple = '''running_mean''' elif "running_var" in name: A: Any = '''running_var''' elif "num_batches_tracked" in name: A: str = '''num_batches_tracked''' else: A: Tuple = None set_recursively(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) continue if not is_used: unused_weights.append(__lowercase ) logger.warning(F"""Unused weights: {unused_weights}""" ) @torch.no_grad() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase=None , __lowercase=None , ) -> Dict: if config_path is not None: A: Tuple = EncodecConfig.from_pretrained(__lowercase ) else: A: Union[str, Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": A: Union[str, Any] = [8, 5, 4, 4] A: Dict = [2.2] A: List[Any] = 6_4 A: Optional[Any] = 3_2_0_0_0 A: List[Any] = 2_0_4_8 A: Optional[Any] = False A: int = False A: Union[str, Any] = False elif model_name == "encodec_48khz": A: Optional[int] = [8, 5, 4, 2] A: List[Any] = [3.0, 6.0, 1_2.0, 2_4.0] A: List[Any] = 4_8_0_0_0 A: int = 2 A: List[Any] = False A: Any = '''time_group_norm''' A: Optional[Any] = True A: Any = 1.0 A: Any = 0.0_1 else: raise ValueError(F"""Unknown model name: {model_name}""" ) A: str = EncodecModel(__lowercase ) A: Optional[Any] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__lowercase ) A: Union[str, Any] = torch.load(__lowercase ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights A: Optional[int] = original_checkpoint['''best_state'''] recursively_load_weights(__lowercase , __lowercase , __lowercase ) model.save_pretrained(__lowercase ) if repo_id: print('''Pushing to the hub...''' ) feature_extractor.push_to_hub(__lowercase ) model.push_to_hub(__lowercase ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) UpperCamelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
334
0
'''simple docstring''' from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) # TODO Update this UpperCamelCase = { '''facebook/esm-1b''': '''https://huggingface.co/facebook/esm-1b/resolve/main/config.json''', # See all ESM models at https://huggingface.co/models?filter=esm } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : List[Any] = """esm""" def __init__( self : Any , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Dict=None , SCREAMING_SNAKE_CASE_ : int=7_68 , SCREAMING_SNAKE_CASE_ : Any=12 , SCREAMING_SNAKE_CASE_ : List[str]=12 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=30_72 , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : List[str]=0.1 , SCREAMING_SNAKE_CASE_ : int=10_26 , SCREAMING_SNAKE_CASE_ : Tuple=0.02 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1E-12 , SCREAMING_SNAKE_CASE_ : Optional[Any]="absolute" , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : Optional[Any]=False , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Tuple=None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , mask_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Dict = vocab_size A: List[Any] = hidden_size A: int = num_hidden_layers A: List[Any] = num_attention_heads A: Union[str, Any] = intermediate_size A: Optional[int] = hidden_dropout_prob A: Union[str, Any] = attention_probs_dropout_prob A: List[str] = max_position_embeddings A: Any = initializer_range A: Union[str, Any] = layer_norm_eps A: Any = position_embedding_type A: List[str] = use_cache A: Dict = emb_layer_norm_before A: Dict = token_dropout A: List[Any] = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) A: List[Any] = EsmFoldConfig() elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A: List[str] = EsmFoldConfig(**SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) A: List[Any] = get_default_vocab_list() else: A: Union[str, Any] = vocab_list else: A: Optional[int] = None A: Optional[Any] = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , SCREAMING_SNAKE_CASE_ ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def _snake_case ( self : str ) -> int: '''simple docstring''' A: List[Any] = super().to_dict() if isinstance(self.esmfold_config , SCREAMING_SNAKE_CASE_ ): A: int = self.esmfold_config.to_dict() return output @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : str = None UpperCamelCase_ : bool = True UpperCamelCase_ : bool = False UpperCamelCase_ : bool = False UpperCamelCase_ : bool = False UpperCamelCase_ : float = 0 UpperCamelCase_ : bool = True UpperCamelCase_ : bool = False UpperCamelCase_ : int = 128 UpperCamelCase_ : "TrunkConfig" = None def _snake_case ( self : List[Any] ) -> int: '''simple docstring''' if self.trunk is None: A: Optional[Any] = TrunkConfig() elif isinstance(self.trunk , SCREAMING_SNAKE_CASE_ ): A: List[Any] = TrunkConfig(**self.trunk ) def _snake_case ( self : str ) -> int: '''simple docstring''' A: Optional[Any] = asdict(self ) A: List[str] = self.trunk.to_dict() return output @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : int = 48 UpperCamelCase_ : int = 1024 UpperCamelCase_ : int = 128 UpperCamelCase_ : int = 32 UpperCamelCase_ : int = 32 UpperCamelCase_ : int = 32 UpperCamelCase_ : float = 0 UpperCamelCase_ : float = 0 UpperCamelCase_ : bool = False UpperCamelCase_ : int = 4 UpperCamelCase_ : Optional[int] = 128 UpperCamelCase_ : "StructureModuleConfig" = None def _snake_case ( self : str ) -> str: '''simple docstring''' if self.structure_module is None: A: Dict = StructureModuleConfig() elif isinstance(self.structure_module , SCREAMING_SNAKE_CASE_ ): A: str = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" ) A: Any = self.sequence_state_dim // self.sequence_head_width A: Tuple = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" ) if self.dropout >= 0.4: raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" ) def _snake_case ( self : List[str] ) -> int: '''simple docstring''' A: int = asdict(self ) A: Tuple = self.structure_module.to_dict() return output @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : int = 384 UpperCamelCase_ : int = 128 UpperCamelCase_ : int = 16 UpperCamelCase_ : int = 128 UpperCamelCase_ : int = 12 UpperCamelCase_ : int = 4 UpperCamelCase_ : int = 8 UpperCamelCase_ : float = 0.1 UpperCamelCase_ : int = 8 UpperCamelCase_ : int = 1 UpperCamelCase_ : int = 2 UpperCamelCase_ : int = 7 UpperCamelCase_ : int = 10 UpperCamelCase_ : float = 1e-8 UpperCamelCase_ : float = 1e5 def _snake_case ( self : int ) -> str: '''simple docstring''' return asdict(self ) def SCREAMING_SNAKE_CASE( ) -> Tuple: return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
354
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' from manim import * class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def _snake_case ( self : int ) -> int: '''simple docstring''' A: List[str] = Rectangle(height=0.5 , width=0.5 ) A: str = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) A: List[str] = Rectangle(height=0.25 , width=0.25 ) A: List[Any] = [mem.copy() for i in range(6 )] A: int = [mem.copy() for i in range(6 )] A: Optional[Any] = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: Any = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: int = VGroup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: Union[str, Any] = Text('''CPU''' , font_size=24 ) A: str = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(SCREAMING_SNAKE_CASE_ ) A: List[str] = [mem.copy() for i in range(4 )] A: Union[str, Any] = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: Any = Text('''GPU''' , font_size=24 ) A: Union[str, Any] = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) gpu.move_to([-1, -1, 0] ) self.add(SCREAMING_SNAKE_CASE_ ) A: Dict = [mem.copy() for i in range(6 )] A: Optional[int] = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: int = Text('''Model''' , font_size=24 ) A: str = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) model.move_to([3, -1.0, 0] ) self.add(SCREAMING_SNAKE_CASE_ ) A: Any = [] A: str = [] for i, rect in enumerate(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = fill.copy().set_fill(SCREAMING_SNAKE_CASE_ , opacity=0.8 ) target.move_to(SCREAMING_SNAKE_CASE_ ) model_arr.append(SCREAMING_SNAKE_CASE_ ) A: str = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(SCREAMING_SNAKE_CASE_ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(SCREAMING_SNAKE_CASE_ ) self.add(*SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) A: int = [meta_mem.copy() for i in range(6 )] A: Dict = [meta_mem.copy() for i in range(6 )] A: int = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: Optional[int] = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: List[str] = VGroup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) A: List[Any] = Text('''Disk''' , font_size=24 ) A: Union[str, Any] = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) disk.move_to([-4, -1.25, 0] ) self.add(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) A: 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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(SCREAMING_SNAKE_CASE_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(SCREAMING_SNAKE_CASE_ ) A: str = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE_ ) ) A: Union[str, Any] = Square(0.3 ) input.set_fill(SCREAMING_SNAKE_CASE_ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , SCREAMING_SNAKE_CASE_ , buff=0.5 ) self.play(Write(SCREAMING_SNAKE_CASE_ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=SCREAMING_SNAKE_CASE_ , buff=0.02 ) self.play(MoveToTarget(SCREAMING_SNAKE_CASE_ ) ) self.play(FadeOut(SCREAMING_SNAKE_CASE_ ) ) A: Dict = Arrow(start=SCREAMING_SNAKE_CASE_ , end=SCREAMING_SNAKE_CASE_ , color=SCREAMING_SNAKE_CASE_ , buff=0.5 ) a.next_to(model_arr[0].get_left() , SCREAMING_SNAKE_CASE_ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) A: Optional[int] = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE_ , run_time=3 ) ) A: Union[str, Any] = {'''run_time''': 1, '''fade_in''': True, '''fade_out''': True, '''buff''': 0.02} self.play( Write(SCREAMING_SNAKE_CASE_ ) , Circumscribe(model_arr[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(model_cpu_arr[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(gpu_rect[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) A: Any = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , SCREAMING_SNAKE_CASE_ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) A: Tuple = AnimationGroup( FadeOut(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , MoveToTarget(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , FadeIn(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(SCREAMING_SNAKE_CASE_ ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: A: Optional[Any] = 0.7 self.play( Circumscribe(model_arr[i] , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(cpu_left_col_base[i] , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(cpu_left_col_base[i + 1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(gpu_rect[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(model_arr[i + 1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(cpu_left_col_base[-1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(gpu_rect[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) A: Union[str, Any] = a_c A: Optional[int] = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(SCREAMING_SNAKE_CASE_ ) , FadeOut(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , ) A: Tuple = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE_ , run_time=3 ) , MoveToTarget(SCREAMING_SNAKE_CASE_ ) ) self.wait()
355
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for data in source_data: for i, el in enumerate(__lowercase ): if len(__lowercase ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__lowercase ) ) return data_lists def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for dlist, weight in zip(__lowercase , __lowercase ): A: List[str] = min(__lowercase ) A: Union[str, Any] = max(__lowercase ) A: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: A: List[str] = F"""Invalid weight of {weight:f} provided""" raise ValueError(__lowercase ) score_lists.append(__lowercase ) return score_lists def SCREAMING_SNAKE_CASE( __lowercase ) -> list[float]: A: list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__lowercase ): A: str = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: Any = get_data(__lowercase ) A: str = calculate_each_score(__lowercase , __lowercase ) A: int = generate_final_scores(__lowercase ) # append scores to source data for i, ele in enumerate(__lowercase ): source_data[i].append(__lowercase ) return source_data
334
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''xlm-mlm-en-2048''': '''https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json''', '''xlm-mlm-ende-1024''': '''https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json''', '''xlm-mlm-enfr-1024''': '''https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json''', '''xlm-mlm-enro-1024''': '''https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json''', '''xlm-mlm-tlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json''', '''xlm-mlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json''', '''xlm-clm-enfr-1024''': '''https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json''', '''xlm-clm-ende-1024''': '''https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json''', '''xlm-mlm-17-1280''': '''https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json''', '''xlm-mlm-100-1280''': '''https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json''', } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : str = """xlm""" UpperCamelCase_ : Any = { """hidden_size""": """emb_dim""", """num_attention_heads""": """n_heads""", """num_hidden_layers""": """n_layers""", """n_words""": """vocab_size""", # For backward compatibility } def __init__( self : int , SCREAMING_SNAKE_CASE_ : Optional[Any]=3_01_45 , SCREAMING_SNAKE_CASE_ : Dict=20_48 , SCREAMING_SNAKE_CASE_ : Dict=12 , SCREAMING_SNAKE_CASE_ : Tuple=16 , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : Optional[int]=True , SCREAMING_SNAKE_CASE_ : str=False , SCREAMING_SNAKE_CASE_ : Tuple=False , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False , SCREAMING_SNAKE_CASE_ : int=1 , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Optional[int]=5_12 , SCREAMING_SNAKE_CASE_ : Dict=20_48**-0.5 , SCREAMING_SNAKE_CASE_ : Optional[int]=1E-12 , SCREAMING_SNAKE_CASE_ : str=0.02 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE_ : str=1 , SCREAMING_SNAKE_CASE_ : Optional[int]=2 , SCREAMING_SNAKE_CASE_ : Tuple=3 , SCREAMING_SNAKE_CASE_ : str=5 , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : int="first" , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE_ : str=5 , SCREAMING_SNAKE_CASE_ : List[str]=5 , SCREAMING_SNAKE_CASE_ : Any=0 , SCREAMING_SNAKE_CASE_ : List[str]=0 , SCREAMING_SNAKE_CASE_ : List[str]=2 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0 , **SCREAMING_SNAKE_CASE_ : Optional[Any] , ) -> Tuple: '''simple docstring''' A: int = vocab_size A: Dict = emb_dim A: int = n_layers A: Optional[Any] = n_heads A: List[Any] = dropout A: Union[str, Any] = attention_dropout A: int = gelu_activation A: str = sinusoidal_embeddings A: Union[str, Any] = causal A: Tuple = asm A: Optional[Any] = n_langs A: Any = use_lang_emb A: List[str] = layer_norm_eps A: Tuple = bos_index A: Tuple = eos_index A: Optional[Any] = pad_index A: Optional[Any] = unk_index A: Optional[Any] = mask_index A: List[str] = is_encoder A: Any = max_position_embeddings A: Optional[int] = embed_init_std A: Tuple = init_std A: Optional[Any] = summary_type A: str = summary_use_proj A: str = summary_activation A: Optional[Any] = summary_proj_to_labels A: Tuple = summary_first_dropout A: Any = start_n_top A: Union[str, Any] = end_n_top A: Optional[int] = mask_token_id A: Optional[int] = lang_id if "n_words" in kwargs: A: Optional[int] = kwargs['''n_words'''] super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' @property def _snake_case ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": A: Union[str, Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A: Optional[Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
356
'''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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = DPRContextEncoderTokenizer class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Dict = VOCAB_FILES_NAMES UpperCamelCase_ : List[str] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Tuple = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Optional[int] = DPRQuestionEncoderTokenizer UpperCamelCase = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) UpperCamelCase = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) UpperCamelCase = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ : '''simple docstring''' def __call__( self : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchEncoding: '''simple docstring''' if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) elif titles is None or texts is None: A: Union[str, Any] = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = titles if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [titles] A: Optional[Any] = texts if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [texts] A: str = len(SCREAMING_SNAKE_CASE_ ) A: List[Any] = questions if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [questions] * n_passages assert len(SCREAMING_SNAKE_CASE_ ) == len( SCREAMING_SNAKE_CASE_ ), f"""There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE_ )} titles and {len(SCREAMING_SNAKE_CASE_ )} texts.""" A: Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: Dict = super().__call__(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: str = { '''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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] } if return_attention_mask is not False: A: Union[str, Any] = [] 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: Optional[Any] = attention_mask return self.pad(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : BatchEncoding , SCREAMING_SNAKE_CASE_ : DPRReaderOutput , SCREAMING_SNAKE_CASE_ : int = 16 , SCREAMING_SNAKE_CASE_ : int = 64 , SCREAMING_SNAKE_CASE_ : int = 4 , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Any = reader_input['''input_ids'''] A , A , A: str = reader_output[:3] A: str = len(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = sorted(range(SCREAMING_SNAKE_CASE_ ) , reverse=SCREAMING_SNAKE_CASE_ , key=relevance_logits.__getitem__ ) A: List[DPRReaderOutput] = [] for doc_id in sorted_docs: A: List[str] = 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: Union[str, Any] = sequence_ids.index(self.pad_token_id ) else: A: int = len(SCREAMING_SNAKE_CASE_ ) A: Dict = 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=SCREAMING_SNAKE_CASE_ , top_spans=SCREAMING_SNAKE_CASE_ , ) 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=SCREAMING_SNAKE_CASE_ , start_index=SCREAMING_SNAKE_CASE_ , end_index=SCREAMING_SNAKE_CASE_ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE_ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Union[str, Any] = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE_ ): 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: Any = sorted(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : x[1] , reverse=SCREAMING_SNAKE_CASE_ ) A: Dict = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]""" A: int = 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(SCREAMING_SNAKE_CASE_ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] = READER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = READER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : Optional[Any] = DPRReaderTokenizer
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print('''Program to check whether a number is a Perfect number or not...''') UpperCamelCase = int(input('''Enter number: ''').strip()) print(f'{number} is {"" if perfect(number) else "not "}a Perfect Number.')
357
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 UpperCamelCase = get_tests_dir('''fixtures''') class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : str ) -> Tuple: '''simple docstring''' A: str = mock.Mock() A: Tuple = 5_00 A: Optional[Any] = {} A: Tuple = HTTPError A: int = {} # Download this model to make sure it's in the cache. A: Dict = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: A: List[Any] = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self : Union[str, Any] ) -> str: '''simple docstring''' A: Dict = WavaVecaFeatureExtractor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json''' ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @classmethod def _snake_case ( cls : List[str] ) -> Any: '''simple docstring''' A: Any = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def _snake_case ( cls : List[str] ) -> List[str]: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-feature-extractor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-feature-extractor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-feature-extractor''' ) except HTTPError: pass def _snake_case ( self : Any ) -> Any: '''simple docstring''' A: Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) feature_extractor.push_to_hub('''test-feature-extractor''' , use_auth_token=self._token ) A: Tuple = WavaVecaFeatureExtractor.from_pretrained(f"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''test-feature-extractor''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) A: int = WavaVecaFeatureExtractor.from_pretrained(f"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : Optional[Any] ) -> List[str]: '''simple docstring''' A: Dict = WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) feature_extractor.push_to_hub('''valid_org/test-feature-extractor''' , use_auth_token=self._token ) A: Tuple = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-feature-extractor-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) A: Tuple = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : Any ) -> Tuple: '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() A: Optional[int] = CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) feature_extractor.push_to_hub('''test-dynamic-feature-extractor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''} , ) A: Tuple = AutoFeatureExtractor.from_pretrained( f"""{USER}/test-dynamic-feature-extractor""" , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , '''CustomFeatureExtractor''' )
358
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' pass class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> None: '''simple docstring''' A: Any = data A: Node | None = None def __iter__( self : Optional[int] ) -> List[str]: '''simple docstring''' A: List[str] = self A: Dict = [] while node: if node in visited: raise ContainsLoopError visited.append(SCREAMING_SNAKE_CASE_ ) yield node.data A: str = node.next_node @property def _snake_case ( self : List[str] ) -> bool: '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": UpperCamelCase = Node(1) UpperCamelCase = Node(2) UpperCamelCase = Node(3) UpperCamelCase = Node(4) print(root_node.has_loop) # False UpperCamelCase = root_node.next_node print(root_node.has_loop) # True UpperCamelCase = Node(5) UpperCamelCase = Node(6) UpperCamelCase = Node(5) UpperCamelCase = Node(6) print(root_node.has_loop) # False UpperCamelCase = Node(1) print(root_node.has_loop) # False
334
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Dict ) -> Any: '''simple docstring''' A: Any = mock.Mock() A: List[Any] = 5_00 A: Optional[int] = {} A: Dict = HTTPError A: Dict = {} # Download this model to make sure it's in the cache. A: str = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: A: str = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _snake_case ( self : Optional[Any] ) -> List[str]: '''simple docstring''' A: Tuple = mock.Mock() A: List[str] = 5_00 A: List[str] = {} A: List[str] = HTTPError A: List[str] = {} # Download this model to make sure it's in the cache. A: Tuple = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: A: Optional[int] = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self : Optional[Any] ) -> Any: '''simple docstring''' try: A: Union[str, Any] = tempfile.mktemp() with open(SCREAMING_SNAKE_CASE_ , '''wb''' ) as f: http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' , SCREAMING_SNAKE_CASE_ ) A: str = AlbertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) finally: os.remove(SCREAMING_SNAKE_CASE_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('''tokenizer.json''' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('''tokenizer.json''' , '''wb''' ) as f: http_get('''https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json''' , SCREAMING_SNAKE_CASE_ ) A: Optional[int] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 10_00 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('''tokenizer.json''' ) def _snake_case ( self : Tuple ) -> Tuple: '''simple docstring''' A: Any = AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] @classmethod def _snake_case ( cls : Any ) -> str: '''simple docstring''' A: str = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def _snake_case ( cls : List[Any] ) -> List[str]: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-tokenizer''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-tokenizer-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-tokenizer''' ) except HTTPError: pass def _snake_case ( self : Optional[int] ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A: int = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: int = BertTokenizer(SCREAMING_SNAKE_CASE_ ) tokenizer.push_to_hub('''test-tokenizer''' , use_auth_token=self._token ) A: List[str] = BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''test-tokenizer''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ , repo_id='''test-tokenizer''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) A: Union[str, Any] = BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def _snake_case ( self : List[Any] ) -> Optional[int]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A: Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: List[str] = BertTokenizer(SCREAMING_SNAKE_CASE_ ) tokenizer.push_to_hub('''valid_org/test-tokenizer-org''' , use_auth_token=self._token ) A: str = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-tokenizer-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-tokenizer-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) A: List[str] = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def _snake_case ( self : Union[str, Any] ) -> Any: '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A: Tuple = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: Union[str, Any] = CustomTokenizer(SCREAMING_SNAKE_CASE_ ) # No fast custom tokenizer tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) A: List[str] = AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A: Tuple = os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) A: Optional[int] = BertTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) bert_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = CustomTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) A: Dict = AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizerFast''' ) A: int = AutoTokenizer.from_pretrained( f"""{USER}/test-dynamic-tokenizer""" , use_fast=SCREAMING_SNAKE_CASE_ , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Any ) -> str: '''simple docstring''' A: Tuple = Trie() trie.add('''Hello 友達''' ) self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) trie.add('''Hello''' ) trie.data self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = Trie() self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS] This is a extra_id_100'''] ) trie.add('''[CLS]''' ) trie.add('''extra_id_1''' ) trie.add('''extra_id_100''' ) self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS]''', ''' This is a ''', '''extra_id_100'''] ) def _snake_case ( self : Union[str, Any] ) -> str: '''simple docstring''' A: Optional[Any] = Trie() trie.add('''A''' ) self.assertEqual(trie.split('''ABC''' ) , ['''A''', '''BC'''] ) self.assertEqual(trie.split('''BCA''' ) , ['''BC''', '''A'''] ) def _snake_case ( self : Dict ) -> Optional[Any]: '''simple docstring''' A: Any = Trie() trie.add('''TOKEN]''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def _snake_case ( self : List[Any] ) -> int: '''simple docstring''' A: Optional[int] = Trie() trie.add('''A''' ) trie.add('''P''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def _snake_case ( self : List[Any] ) -> Optional[int]: '''simple docstring''' A: Tuple = Trie() trie.add('''AB''' ) trie.add('''B''' ) trie.add('''C''' ) self.assertEqual(trie.split('''ABC''' ) , ['''AB''', '''C'''] ) def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: Optional[int] = Trie() trie.add('''ABC''' ) trie.add('''B''' ) trie.add('''CD''' ) self.assertEqual(trie.split('''ABCD''' ) , ['''ABC''', '''D'''] ) def _snake_case ( self : Any ) -> Any: '''simple docstring''' A: Union[str, Any] = Trie() A: List[str] = trie.cut_text('''ABC''' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , ['''AB''', '''C'''] )
359
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE( __lowercase = 4 ) -> list[list[int]]: A: Tuple = abs(__lowercase ) or 4 return [[1 + x + y * row_size for x in range(__lowercase )] for y in range(__lowercase )] def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(transpose(__lowercase ) ) # OR.. transpose(reverse_column(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(reverse_column(__lowercase ) ) # OR.. reverse_column(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_column(transpose(__lowercase ) ) # OR.. transpose(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Union[str, Any] = [list(__lowercase ) for x in zip(*__lowercase )] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[int] = matrix[::-1] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[Any] = [x[::-1] for x in matrix] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> None: for i in matrix: print(*__lowercase ) if __name__ == "__main__": UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
334
0
'''simple docstring''' from typing import Dict, Optional import numpy as np import datasets UpperCamelCase = ''' IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation, the mean IoU of the image is calculated by taking the IoU of each class and averaging them. ''' UpperCamelCase = ''' Args: predictions (`List[ndarray]`): List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size. references (`List[ndarray]`): List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size. num_labels (`int`): Number of classes (categories). ignore_index (`int`): Index that will be ignored during evaluation. nan_to_num (`int`, *optional*): If specified, NaN values will be replaced by the number defined by the user. label_map (`dict`, *optional*): If specified, dictionary mapping old label indices to new label indices. reduce_labels (`bool`, *optional*, defaults to `False`): Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255. Returns: `Dict[str, float | ndarray]` comprising various elements: - *mean_iou* (`float`): Mean Intersection-over-Union (IoU averaged over all categories). - *mean_accuracy* (`float`): Mean accuracy (averaged over all categories). - *overall_accuracy* (`float`): Overall accuracy on all images. - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`): Per category accuracy. - *per_category_iou* (`ndarray` of shape `(num_labels,)`): Per category IoU. Examples: >>> import numpy as np >>> mean_iou = datasets.load_metric("mean_iou") >>> # suppose one has 3 different segmentation maps predicted >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]]) >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]]) >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]]) >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]]) >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]]) >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]]) >>> predicted = [predicted_1, predicted_2, predicted_3] >>> ground_truth = [actual_1, actual_2, actual_3] >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False) >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])} ''' UpperCamelCase = '''\ @software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020, author = {{MMSegmentation Contributors}}, license = {Apache-2.0}, month = {7}, title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}}, url = {https://github.com/open-mmlab/mmsegmentation}, year = {2020} }''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase = None , __lowercase = False , ) -> Optional[int]: if label_map is not None: for old_id, new_id in label_map.items(): A: List[Any] = new_id # turn into Numpy arrays A: Union[str, Any] = np.array(__lowercase ) A: Union[str, Any] = np.array(__lowercase ) if reduce_labels: A: List[Any] = 2_5_5 A: Union[str, Any] = label - 1 A: Optional[Any] = 2_5_5 A: Optional[int] = label != ignore_index A: Optional[int] = np.not_equal(__lowercase , __lowercase ) A: Optional[int] = pred_label[mask] A: Optional[int] = np.array(__lowercase )[mask] A: List[Any] = pred_label[pred_label == label] A: int = np.histogram(__lowercase , bins=__lowercase , range=(0, num_labels - 1) )[0] A: List[str] = np.histogram(__lowercase , bins=__lowercase , range=(0, num_labels - 1) )[0] A: str = np.histogram(__lowercase , bins=__lowercase , range=(0, num_labels - 1) )[0] A: Dict = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase = None , __lowercase = False , ) -> List[str]: A: Optional[Any] = np.zeros((num_labels,) , dtype=np.floataa ) A: str = np.zeros((num_labels,) , dtype=np.floataa ) A: Dict = np.zeros((num_labels,) , dtype=np.floataa ) A: Optional[Any] = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(__lowercase , __lowercase ): A: Union[str, Any] = intersect_and_union( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase = None , __lowercase = None , __lowercase = False , ) -> List[Any]: A: List[str] = total_intersect_and_union( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) # compute metrics A: Optional[int] = {} A: Optional[Any] = total_area_intersect.sum() / total_area_label.sum() A: List[Any] = total_area_intersect / total_area_union A: Union[str, Any] = total_area_intersect / total_area_label A: List[Any] = np.nanmean(__lowercase ) A: Dict = np.nanmean(__lowercase ) A: List[str] = all_acc A: List[str] = iou A: List[str] = acc if nan_to_num is not None: A: str = {metric: np.nan_to_num(__lowercase , nan=__lowercase ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self : Any ) -> str: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16''' ) ) ), '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16''' ) ) ), } ) , reference_urls=[ '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py''' ] , ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : bool , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Dict[int, int]] = None , SCREAMING_SNAKE_CASE_ : bool = False , ) -> List[Any]: '''simple docstring''' A: Dict = mean_iou( results=SCREAMING_SNAKE_CASE_ , gt_seg_maps=SCREAMING_SNAKE_CASE_ , num_labels=SCREAMING_SNAKE_CASE_ , ignore_index=SCREAMING_SNAKE_CASE_ , nan_to_num=SCREAMING_SNAKE_CASE_ , label_map=SCREAMING_SNAKE_CASE_ , reduce_labels=SCREAMING_SNAKE_CASE_ , ) return iou_result
360
'''simple docstring''' from __future__ import annotations import numpy as np def SCREAMING_SNAKE_CASE( __lowercase ) -> Dict: return np.maximum(0 , __lowercase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
334
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''facebook/nllb-moe-54B''': '''https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json''', } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = """nllb-moe""" UpperCamelCase_ : List[str] = ["""past_key_values"""] UpperCamelCase_ : int = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any]=12_81_12 , SCREAMING_SNAKE_CASE_ : Dict=10_24 , SCREAMING_SNAKE_CASE_ : List[Any]=12 , SCREAMING_SNAKE_CASE_ : Dict=40_96 , SCREAMING_SNAKE_CASE_ : int=16 , SCREAMING_SNAKE_CASE_ : int=12 , SCREAMING_SNAKE_CASE_ : List[str]=40_96 , SCREAMING_SNAKE_CASE_ : List[Any]=16 , SCREAMING_SNAKE_CASE_ : List[Any]=0.05 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.05 , SCREAMING_SNAKE_CASE_ : List[str]=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : List[Any]="relu" , SCREAMING_SNAKE_CASE_ : str=10_24 , SCREAMING_SNAKE_CASE_ : List[str]=0.1 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE_ : int=0.0 , SCREAMING_SNAKE_CASE_ : List[str]=0.02 , SCREAMING_SNAKE_CASE_ : Any=2 , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : Dict="float32" , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : List[Any]=1_28 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=64 , SCREAMING_SNAKE_CASE_ : str=4 , SCREAMING_SNAKE_CASE_ : str=4 , SCREAMING_SNAKE_CASE_ : List[Any]=0.001 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.001 , SCREAMING_SNAKE_CASE_ : Optional[int]="all" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False , SCREAMING_SNAKE_CASE_ : Any=False , SCREAMING_SNAKE_CASE_ : List[Any]=1.0 , SCREAMING_SNAKE_CASE_ : Any=0.2 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE_ : Tuple=False , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> Optional[Any]: '''simple docstring''' A: List[str] = vocab_size A: Tuple = max_position_embeddings A: str = d_model A: int = encoder_ffn_dim A: Optional[Any] = encoder_layers A: int = encoder_attention_heads A: List[str] = decoder_ffn_dim A: int = decoder_layers A: Any = decoder_attention_heads A: List[str] = dropout A: List[str] = attention_dropout A: Optional[int] = activation_dropout A: List[Any] = activation_function A: List[Any] = init_std A: Optional[int] = encoder_layerdrop A: Any = decoder_layerdrop A: List[str] = use_cache A: Dict = encoder_layers A: Union[str, Any] = scale_embedding # scale factor will be sqrt(d_model) if True A: Tuple = router_z_loss_coef A: Optional[int] = router_aux_loss_coef A: Tuple = decoder_sparse_step A: List[Any] = encoder_sparse_step A: Any = num_experts A: Union[str, Any] = expert_capacity A: List[Any] = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) A: List[str] = router_dtype A: Union[str, Any] = router_ignore_padding_tokens A: Tuple = batch_prioritized_routing A: Optional[Any] = second_expert_policy A: Any = normalize_router_prob_before_dropping A: Tuple = moe_eval_capacity_token_fraction A: Tuple = moe_token_dropout A: Tuple = output_router_logits super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
361
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , *SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Dict ) -> None: '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
362
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
334
0
'''simple docstring''' import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging UpperCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Union[str, Any]: A: Tuple = set() A: int = [] def parse_line(__lowercase ): for line in fp: if isinstance(__lowercase , __lowercase ): A: List[Any] = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(__lowercase ) > 0: A: str = '''\n'''.join(__lowercase ) # Only keep the warnings specified in `targets` if any(F""": {x}: """ in warning for x in targets ): selected_warnings.add(__lowercase ) buffer.clear() continue else: A: Union[str, Any] = line.strip() buffer.append(__lowercase ) if from_gh: for filename in os.listdir(__lowercase ): A: int = os.path.join(__lowercase , __lowercase ) if not os.path.isdir(__lowercase ): # read the file if filename != "warnings.txt": continue with open(__lowercase ) as fp: parse_line(__lowercase ) else: try: with zipfile.ZipFile(__lowercase ) as z: for filename in z.namelist(): if not os.path.isdir(__lowercase ): # read the file if filename != "warnings.txt": continue with z.open(__lowercase ) as fp: parse_line(__lowercase ) except Exception: logger.warning( F"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Any: A: Union[str, Any] = set() A: Optional[int] = [os.path.join(__lowercase , __lowercase ) for p in os.listdir(__lowercase ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(__lowercase , __lowercase ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE( __lowercase ) -> List[Any]: return values.split(''',''' ) UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') # optional parameters parser.add_argument( '''--targets''', default='''DeprecationWarning,UserWarning,FutureWarning''', type=list_str, help='''Comma-separated list of target warning(s) which we want to extract.''', ) parser.add_argument( '''--from_gh''', action='''store_true''', help='''If running from a GitHub action workflow and collecting warnings from its artifacts.''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links UpperCamelCase = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print('''=''' * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts UpperCamelCase = extract_warnings(args.output_dir, args.targets) UpperCamelCase = sorted(selected_warnings) with open(os.path.join(args.output_dir, '''selected_warnings.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
363
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : torch.FloatTensor class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE_ : int = 6_55_36 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : str = "fourier" , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , SCREAMING_SNAKE_CASE_ : Tuple[str] = "UNetMidBlock1D" , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : Tuple[int] = (32, 32, 64) , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : int = 8 , SCREAMING_SNAKE_CASE_ : int = 1 , SCREAMING_SNAKE_CASE_ : bool = False , ) -> Tuple: '''simple docstring''' super().__init__() A: Optional[Any] = sample_size # time if time_embedding_type == "fourier": A: Tuple = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=SCREAMING_SNAKE_CASE_ , log=SCREAMING_SNAKE_CASE_ , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ ) A: List[str] = 2 * block_out_channels[0] elif time_embedding_type == "positional": A: str = Timesteps( block_out_channels[0] , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ , downscale_freq_shift=SCREAMING_SNAKE_CASE_ ) A: Any = block_out_channels[0] if use_timestep_embedding: A: Optional[Any] = block_out_channels[0] * 4 A: List[Any] = TimestepEmbedding( in_channels=SCREAMING_SNAKE_CASE_ , time_embed_dim=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , out_dim=block_out_channels[0] , ) A: Optional[Any] = nn.ModuleList([] ) A: str = None A: str = nn.ModuleList([] ) A: Tuple = None # down A: Any = in_channels for i, down_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = output_channel A: List[Any] = block_out_channels[i] if i == 0: input_channel += extra_in_channels A: List[Any] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[int] = get_down_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(SCREAMING_SNAKE_CASE_ ) # mid A: Union[str, Any] = get_mid_block( SCREAMING_SNAKE_CASE_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=SCREAMING_SNAKE_CASE_ , add_downsample=SCREAMING_SNAKE_CASE_ , ) # up A: Optional[Any] = list(reversed(SCREAMING_SNAKE_CASE_ ) ) A: List[str] = reversed_block_out_channels[0] if out_block_type is None: A: int = out_channels else: A: Union[str, Any] = block_out_channels[0] for i, up_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: List[Any] = output_channel A: int = ( reversed_block_out_channels[i + 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 else final_upsample_channels ) A: Optional[int] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[Any] = get_up_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(SCREAMING_SNAKE_CASE_ ) A: Any = output_channel # out A: List[str] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) A: Optional[int] = get_out_block( out_block_type=SCREAMING_SNAKE_CASE_ , num_groups_out=SCREAMING_SNAKE_CASE_ , embed_dim=block_out_channels[0] , out_channels=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , fc_dim=block_out_channels[-1] // 4 , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : torch.FloatTensor , SCREAMING_SNAKE_CASE_ : Union[torch.Tensor, float, int] , SCREAMING_SNAKE_CASE_ : bool = True , ) -> Union[UNetaDOutput, Tuple]: '''simple docstring''' A: Any = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(SCREAMING_SNAKE_CASE_ ) and len(timesteps.shape ) == 0: A: List[str] = timesteps[None].to(sample.device ) A: int = self.time_proj(SCREAMING_SNAKE_CASE_ ) if self.config.use_timestep_embedding: A: List[Any] = self.time_mlp(SCREAMING_SNAKE_CASE_ ) else: A: str = timestep_embed[..., None] A: Union[str, Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) A: Tuple = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down A: List[str] = () for downsample_block in self.down_blocks: A , A: Optional[int] = downsample_block(hidden_states=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: A: Dict = self.mid_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): A: List[Any] = down_block_res_samples[-1:] A: List[str] = down_block_res_samples[:-1] A: Optional[int] = upsample_block(SCREAMING_SNAKE_CASE_ , res_hidden_states_tuple=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) # 5. post-process if self.out_block: A: Any = self.out_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PLBartForCausalLM''', '''PLBartForConditionalGeneration''', '''PLBartForSequenceClassification''', '''PLBartModel''', '''PLBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
364
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , *SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Dict ) -> None: '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): def __init__( self : Dict , *SCREAMING_SNAKE_CASE_ : List[str] , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> None: '''simple docstring''' warnings.warn( '''The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use PoolFormerImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
365
'''simple docstring''' from collections import deque class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> None: '''simple docstring''' A: Union[str, Any] = process_name # process name A: List[str] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time A: Dict = arrival_time A: Optional[Any] = burst_time # remaining burst time A: Any = 0 # total time of the process wait in ready queue A: Any = 0 # time from arrival time to completion time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int , ) -> None: '''simple docstring''' A: Dict = number_of_queues # time slice of queues that round robin algorithm applied A: int = time_slices # unfinished process is in this ready_queue A: Tuple = queue # current time A: int = current_time # finished process is in this sequence queue A: deque[Process] = deque() def _snake_case ( self : List[Any] ) -> list[str]: '''simple docstring''' A: str = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Optional[int] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Any = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: List[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> list[int]: '''simple docstring''' return [q.burst_time for q in queue] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Process ) -> int: '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> deque[Process]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE_ ) != 0: A: Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 A: Any = 0 # set the process's turnaround time because it is finished A: int = self.current_time - cp.arrival_time # set the completion time A: List[str] = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int ) -> tuple[deque[Process], deque[Process]]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE_ ) ): A: Dict = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time A: Optional[Any] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished A: int = 0 # set the finish time A: Union[str, Any] = self.current_time # update the process' turnaround time because it is finished A: Tuple = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _snake_case ( self : Optional[Any] ) -> deque[Process]: '''simple docstring''' for i in range(self.number_of_queues - 1 ): A , A: Optional[Any] = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])}) UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) UpperCamelCase = MLFQ(number_of_queues, time_slices, queue, 0) UpperCamelCase = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print completion times of processes(P1, P2, P3, P4) print( f'completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print sequence of finished processes print( f'sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}' )
334
0
'''simple docstring''' from maths.prime_factors import prime_factors def SCREAMING_SNAKE_CASE( __lowercase ) -> int: if not isinstance(__lowercase , __lowercase ): A: Any = F"""Input value of [number={number}] must be an integer""" raise TypeError(__lowercase ) if number < 1: raise ValueError('''Input must be a positive integer''' ) return -1 if len(prime_factors(__lowercase ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
366
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : List[nn.Module] = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : list = field(default_factory=UpperCAmelCase_ ) def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tensor , SCREAMING_SNAKE_CASE_ : Tensor ) -> int: '''simple docstring''' A: List[str] = len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE_ , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE_ ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tensor ) -> Dict: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE_ ) [x.remove() for x in self.handles] return self @property def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' return list(filter(lambda SCREAMING_SNAKE_CASE_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : nn.Module UpperCamelCase_ : int = 0 UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) def __call__( self : Any , SCREAMING_SNAKE_CASE_ : Tensor ) -> Optional[Any]: '''simple docstring''' A: Dict = Tracker(self.dest )(SCREAMING_SNAKE_CASE_ ).parametrized A: Tuple = Tracker(self.src )(SCREAMING_SNAKE_CASE_ ).parametrized A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.src_skip , SCREAMING_SNAKE_CASE_ ) ) A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.dest_skip , SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise Exception( f"""Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE_ )} operations while""" f""" destination module has {len(SCREAMING_SNAKE_CASE_ )}.""" ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = True ) -> Any: print(F"""Converting {name}...""" ) with torch.no_grad(): A: Union[str, Any] = timm.create_model(__lowercase , pretrained=__lowercase ).eval() A: List[str] = ResNetForImageClassification(__lowercase ).eval() A: int = ModuleTransfer(src=__lowercase , dest=__lowercase ) A: List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(__lowercase ) assert torch.allclose(from_model(__lowercase ) , our_model(__lowercase ).logits ), "The model logits don't match the original one." A: str = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(__lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=__lowercase , ) # we can use the convnext one A: Any = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=__lowercase , ) print(F"""Pushed {checkpoint_name}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = None , __lowercase = True ) -> List[Any]: A: Union[str, Any] = '''imagenet-1k-id2label.json''' A: Union[str, Any] = 1_0_0_0 A: Optional[int] = (1, num_labels) A: Dict = '''huggingface/label-files''' A: Any = num_labels A: Union[str, Any] = json.load(open(hf_hub_download(__lowercase , __lowercase , repo_type='''dataset''' ) , '''r''' ) ) A: Optional[int] = {int(__lowercase ): v for k, v in idalabel.items()} A: Optional[int] = idalabel A: List[str] = {v: k for k, v in idalabel.items()} A: str = partial(__lowercase , num_labels=__lowercase , idalabel=__lowercase , labelaid=__lowercase ) A: Optional[Any] = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(__lowercase , names_to_config[model_name] , __lowercase , __lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowercase , __lowercase , __lowercase , __lowercase ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : int = """pegasus""" UpperCamelCase_ : Tuple = ["""past_key_values"""] UpperCamelCase_ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int]=5_02_65 , SCREAMING_SNAKE_CASE_ : str=10_24 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=12 , SCREAMING_SNAKE_CASE_ : Optional[int]=40_96 , SCREAMING_SNAKE_CASE_ : str=16 , SCREAMING_SNAKE_CASE_ : Dict=12 , SCREAMING_SNAKE_CASE_ : List[str]=40_96 , SCREAMING_SNAKE_CASE_ : Optional[int]=16 , SCREAMING_SNAKE_CASE_ : List[str]=0.0 , SCREAMING_SNAKE_CASE_ : List[Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Optional[int]=True , SCREAMING_SNAKE_CASE_ : Any="gelu" , SCREAMING_SNAKE_CASE_ : Optional[int]=10_24 , SCREAMING_SNAKE_CASE_ : List[Any]=0.1 , SCREAMING_SNAKE_CASE_ : List[Any]=0.0 , SCREAMING_SNAKE_CASE_ : str=0.0 , SCREAMING_SNAKE_CASE_ : Any=0.02 , SCREAMING_SNAKE_CASE_ : Dict=0 , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : Any=0 , SCREAMING_SNAKE_CASE_ : List[Any]=1 , SCREAMING_SNAKE_CASE_ : int=1 , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Tuple: '''simple docstring''' A: int = vocab_size A: Dict = max_position_embeddings A: List[str] = d_model A: Tuple = encoder_ffn_dim A: Any = encoder_layers A: List[str] = encoder_attention_heads A: str = decoder_ffn_dim A: List[str] = decoder_layers A: Union[str, Any] = decoder_attention_heads A: Tuple = dropout A: Optional[Any] = attention_dropout A: Dict = activation_dropout A: List[str] = activation_function A: List[Any] = init_std A: List[Any] = encoder_layerdrop A: Optional[int] = decoder_layerdrop A: str = use_cache A: int = encoder_layers A: Optional[int] = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @property def _snake_case ( self : Any ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def _snake_case ( self : str ) -> int: '''simple docstring''' return self.d_model
367
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str | Literal[False]: A: List[str] = list(__lowercase ) A: Optional[Any] = list(__lowercase ) A: int = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count += 1 A: Optional[Any] = '''_''' if count > 1: return False else: return "".join(__lowercase ) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[str]: A: Any = [] while True: A: Dict = ['''$'''] * len(__lowercase ) A: Union[str, Any] = [] for i in range(len(__lowercase ) ): for j in range(i + 1 , len(__lowercase ) ): A: Any = compare_string(binary[i] , binary[j] ) if k is False: A: Any = '''*''' A: List[Any] = '''*''' temp.append('''X''' ) for i in range(len(__lowercase ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__lowercase ) == 0: return pi A: List[Any] = list(set(__lowercase ) ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: Optional[int] = [] for minterm in minterms: A: Optional[int] = '''''' for _ in range(__lowercase ): A: List[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(__lowercase ) return temp def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> bool: A: Union[str, Any] = list(__lowercase ) A: Union[str, Any] = list(__lowercase ) A: Optional[int] = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: List[Any] = [] A: Dict = [0] * len(__lowercase ) for i in range(len(chart[0] ) ): A: List[str] = 0 A: str = -1 for j in range(len(__lowercase ) ): if chart[j][i] == 1: count += 1 A: Any = j if count == 1: A: Any = 1 for i in range(len(__lowercase ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(__lowercase ) ): A: Optional[int] = 0 temp.append(prime_implicants[i] ) while True: A: Dict = 0 A: Optional[int] = -1 A: Dict = 0 for i in range(len(__lowercase ) ): A: str = chart[i].count(1 ) if count_n > max_n: A: Tuple = count_n A: Optional[Any] = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(__lowercase ) ): A: Any = 0 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[int]]: A: str = [[0 for x in range(len(__lowercase ) )] for x in range(len(__lowercase ) )] for i in range(len(__lowercase ) ): A: Tuple = prime_implicants[i].count('''_''' ) for j in range(len(__lowercase ) ): if is_for_table(prime_implicants[i] , binary[j] , __lowercase ): A: Optional[Any] = 1 return chart def SCREAMING_SNAKE_CASE( ) -> None: A: int = int(input('''Enter the no. of variables\n''' ) ) A: Optional[int] = [ float(__lowercase ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] A: List[str] = decimal_to_binary(__lowercase , __lowercase ) A: str = check(__lowercase ) print('''Prime Implicants are:''' ) print(__lowercase ) A: List[Any] = prime_implicant_chart(__lowercase , __lowercase ) A: Any = selection(__lowercase , __lowercase ) print('''Essential Prime Implicants are:''' ) print(__lowercase ) if __name__ == "__main__": import doctest doctest.testmod() main()
334
0
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 UpperCamelCase = get_tests_dir('''fixtures''') UpperCamelCase = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''') UpperCamelCase = get_tests_dir('''fixtures/dummy-config.json''') class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : int ) -> List[Any]: '''simple docstring''' A: Optional[Any] = 0 def _snake_case ( self : str ) -> str: '''simple docstring''' A: List[Any] = AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : str ) -> Any: '''simple docstring''' A: str = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[str] ) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: A: str = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally A: Any = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ).to_dict() config_dict.pop('''feature_extractor_type''' ) A: Dict = WavaVecaFeatureExtractor(**SCREAMING_SNAKE_CASE_ ) # save in new folder model_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) config.save_pretrained(SCREAMING_SNAKE_CASE_ ) A: Tuple = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) # make sure private variable is not incorrectly saved A: Optional[int] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Dict ) -> List[Any]: '''simple docstring''' A: Tuple = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''bert-base is not a local folder and is not a valid model identifier''' ): A: Any = AutoFeatureExtractor.from_pretrained('''bert-base''' ) def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): A: Optional[Any] = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ , revision='''aaaaaa''' ) def _snake_case ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): A: Any = AutoFeatureExtractor.from_pretrained('''hf-internal-testing/config-no-model''' ) def _snake_case ( self : List[str] ) -> List[str]: '''simple docstring''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = AutoFeatureExtractor.from_pretrained( '''hf-internal-testing/test_dynamic_feature_extractor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(SCREAMING_SNAKE_CASE_ ): A: Tuple = AutoFeatureExtractor.from_pretrained( '''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) A: Any = AutoFeatureExtractor.from_pretrained( '''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) A: List[str] = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' ) def _snake_case ( self : int ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE_ ) AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE_ ): AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Now that the config is registered, it can be used as any other config with the auto-API A: List[Any] = CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) A: Any = AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def _snake_case ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : int = True try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE_ ) AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # If remote code is not set, the default is to use local A: List[Any] = AutoFeatureExtractor.from_pretrained( '''hf-internal-testing/test_dynamic_feature_extractor''' ) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. A: Optional[Any] = AutoFeatureExtractor.from_pretrained( '''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub A: Optional[int] = AutoFeatureExtractor.from_pretrained( '''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' ) self.assertTrue(not hasattr(SCREAMING_SNAKE_CASE_ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
368
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> Tuple: A: Tuple = len(__lowercase ) for i in range(length - 1 ): A: Dict = i for k in range(i + 1 , __lowercase ): if collection[k] < collection[least]: A: List[str] = k if least != i: A , A: Tuple = (collection[i], collection[least]) return collection if __name__ == "__main__": UpperCamelCase = input('''Enter numbers separated by a comma:\n''').strip() UpperCamelCase = [int(item) for item in user_input.split(''',''')] print(selection_sort(unsorted))
334
0
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json UpperCamelCase = '''sshleifer/mar_enro_6_3_student''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def _snake_case ( self : Dict ) -> Dict: '''simple docstring''' super().setUp() A: str = cached_path( '''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = f"""{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k""" @slow @require_torch_gpu def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' MarianMTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) @slow @require_torch_gpu def _snake_case ( self : int ) -> Dict: '''simple docstring''' A: Dict = { '''$MAX_LEN''': 64, '''$BS''': 64, '''$GAS''': 1, '''$ENRO_DIR''': self.data_dir, '''facebook/mbart-large-cc25''': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '''--learning_rate=3e-5''': '''--learning_rate 3e-4''', '''--num_train_epochs 6''': '''--num_train_epochs 1''', } # Clean up bash script A: Any = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip() A: Any = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) for k, v in env_vars_to_replace.items(): A: Optional[Any] = bash_script.replace(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) A: Any = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") A: str = f""" --output_dir {output_dir} --tokenizer_name Helsinki-NLP/opus-mt-en-ro --sortish_sampler --do_predict --gpus 1 --freeze_encoder --n_train 40000 --n_val 500 --n_test 500 --fp16_opt_level O1 --num_sanity_val_steps 0 --eval_beams 2 """.split() # XXX: args.gpus > 1 : handle multi_gpu in the future A: int = ['''finetune.py'''] + bash_script.split() + args with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = argparse.ArgumentParser() A: Optional[int] = pl.Trainer.add_argparse_args(SCREAMING_SNAKE_CASE_ ) A: List[Any] = SummarizationModule.add_model_specific_args(SCREAMING_SNAKE_CASE_ , os.getcwd() ) A: int = parser.parse_args() A: List[str] = main(SCREAMING_SNAKE_CASE_ ) # Check metrics A: List[Any] = load_json(model.metrics_save_path ) A: Union[str, Any] = metrics['''val'''][0] A: List[str] = metrics['''val'''][-1] self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , SCREAMING_SNAKE_CASE_ ) self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict A: Optional[Any] = os.listdir(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = [x for x in contents if x.endswith('''.ckpt''' )][0] A: Any = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE_ ) A: List[Any] = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) A: int = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: A: List[str] = {os.path.basename(SCREAMING_SNAKE_CASE_ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1 class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' @timeout_decorator.timeout(6_00 ) @slow @require_torch_gpu def _snake_case ( self : Dict ) -> str: '''simple docstring''' A: List[str] = f"""{self.test_file_dir_str}/test_data/wmt_en_ro""" A: str = { '''--fp16_opt_level=O1''': '''''', '''$MAX_LEN''': 1_28, '''$BS''': 16, '''$GAS''': 1, '''$ENRO_DIR''': data_dir, '''$m''': '''sshleifer/student_marian_en_ro_6_1''', '''val_check_interval=0.25''': '''val_check_interval=1.0''', } # Clean up bash script A: List[Any] = ( (self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip() ) A: Optional[int] = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' ) A: str = bash_script.replace('''--fp16 ''' , ''' ''' ) for k, v in env_vars_to_replace.items(): A: Tuple = bash_script.replace(SCREAMING_SNAKE_CASE_ , str(SCREAMING_SNAKE_CASE_ ) ) A: List[Any] = self.get_auto_remove_tmp_dir() A: List[Any] = bash_script.replace('''--fp16''' , '''''' ) A: int = 6 A: int = ( ['''distillation.py'''] + bash_script.split() + [ f"""--output_dir={output_dir}""", '''--gpus=1''', '''--learning_rate=1e-3''', f"""--num_train_epochs={epochs}""", '''--warmup_steps=10''', '''--val_check_interval=1.0''', '''--do_predict''', ] ) with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): A: List[Any] = argparse.ArgumentParser() A: List[Any] = pl.Trainer.add_argparse_args(SCREAMING_SNAKE_CASE_ ) A: List[str] = SummarizationDistiller.add_model_specific_args(SCREAMING_SNAKE_CASE_ , os.getcwd() ) A: List[str] = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu A: Optional[Any] = distill_main(SCREAMING_SNAKE_CASE_ ) # Check metrics A: List[str] = load_json(model.metrics_save_path ) A: Any = metrics['''val'''][0] A: Tuple = metrics['''val'''][-1] assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , SCREAMING_SNAKE_CASE_ ) # check lightning ckpt can be loaded and has a reasonable statedict A: Any = os.listdir(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [x for x in contents if x.endswith('''.ckpt''' )][0] A: Optional[Any] = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE_ ) A: Tuple = torch.load(SCREAMING_SNAKE_CASE_ , map_location='''cpu''' ) A: List[str] = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight''' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: A: Optional[Any] = {os.path.basename(SCREAMING_SNAKE_CASE_ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['''test'''] ) == 1
369
'''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> int: '''simple docstring''' A: Tuple = None A: Dict = None A: Optional[int] = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: str = len(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = None def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ) -> str: '''simple docstring''' if sources is int: A: Union[str, Any] = [sources] if sinks is int: A: Tuple = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return A: List[str] = sources[0] A: Optional[int] = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: A: Any = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A: Dict = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A: Optional[Any] = max_input_flow A: Optional[Any] = 0 A: str = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A: Optional[Any] = max_input_flow A: str = size - 1 def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple: '''simple docstring''' A: Optional[Any] = algorithm(self ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: '''simple docstring''' A: str = flow_network A: List[str] = flow_network.verticesCount A: Dict = flow_network.sourceIndex A: Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A: str = flow_network.graph A: str = False def _snake_case ( self : int ) -> Union[str, Any]: '''simple docstring''' if not self.executed: self._algorithm() A: str = True def _snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' pass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result A: Any = -1 def _snake_case ( self : List[str] ) -> Optional[Any]: '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [[0] * self.verticies_count for i in range(self.verticies_count )] A: Any = [0] * self.verticies_count A: Optional[Any] = [0] * self.verticies_count def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' A: Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A: str = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A: Dict = 0 while i < len(SCREAMING_SNAKE_CASE_ ): A: Any = vertices_list[i] A: str = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) A: Tuple = 0 else: i += 1 A: Tuple = sum(self.preflow[self.source_index] ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: '''simple docstring''' A: Optional[int] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str ) -> int: '''simple docstring''' A: Optional[Any] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A: List[Any] = self.heights[to_index] if min_height is not None: A: int = min_height + 1 if __name__ == "__main__": UpperCamelCase = [0] UpperCamelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCamelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCamelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCamelCase = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
334
0
'''simple docstring''' import itertools import string from collections.abc import Generator, Iterable def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Generator[tuple[str, ...], None, None]: A: List[str] = iter(__lowercase ) while True: A: int = tuple(itertools.islice(__lowercase , __lowercase ) ) if not chunk: return yield chunk def SCREAMING_SNAKE_CASE( __lowercase ) -> str: A: int = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] ) A: Dict = '''''' if len(__lowercase ) < 2: return dirty for i in range(len(__lowercase ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(__lowercase ) & 1: clean += "X" return clean def SCREAMING_SNAKE_CASE( __lowercase ) -> list[str]: # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) A: Union[str, Any] = '''ABCDEFGHIKLMNOPQRSTUVWXYZ''' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler A: Any = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(__lowercase ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(__lowercase ) return table def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str: A: str = generate_table(__lowercase ) A: int = prepare_input(__lowercase ) A: str = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(__lowercase , 2 ): A: Dict = divmod(table.index(__lowercase ) , 5 ) A: Any = divmod(table.index(__lowercase ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str: A: List[Any] = generate_table(__lowercase ) A: Union[str, Any] = '''''' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(__lowercase , 2 ): A: str = divmod(table.index(__lowercase ) , 5 ) A: Dict = divmod(table.index(__lowercase ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
370
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
334
0
'''simple docstring''' import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( '''split_dict''' , [ SplitDict(), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1_3_3_7 , num_examples=4_2 , dataset_name='''my_dataset''' )} ), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1_3_3_7 , num_examples=4_2 )} ), SplitDict({'''train''': SplitInfo()} ), ] , ) def SCREAMING_SNAKE_CASE( __lowercase ) -> Any: A: List[str] = split_dict._to_yaml_list() assert len(__lowercase ) == len(__lowercase ) A: Optional[Any] = SplitDict._from_yaml_list(__lowercase ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump A: Tuple = None # the split name of split_dict takes over the name of the split info object A: int = split_name assert split_dict == reloaded @pytest.mark.parametrize( '''split_info''' , [SplitInfo(), SplitInfo(dataset_name=__lowercase ), SplitInfo(dataset_name='''my_dataset''' )] ) def SCREAMING_SNAKE_CASE( __lowercase ) -> Any: # For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name" # field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files A: Any = asdict(SplitDict({'''train''': split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
371
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = DebertaTokenizer UpperCamelCase_ : List[str] = True UpperCamelCase_ : int = DebertaTokenizerFast def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A: Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] A: int = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A: Union[str, Any] = {'''unk_token''': '''[UNK]'''} A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: str = 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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : int , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = '''lower newer''' A: str = '''lower newer''' return input_text, output_text def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: str = self.get_tokenizer() A: Any = '''lower newer''' A: Dict = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] A: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokens + [tokenizer.unk_token] A: int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' A: str = self.get_tokenizer() A: List[str] = tokenizer('''Hello''' , '''World''' ) A: Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Tuple ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) A: int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _snake_case ( self : Tuple ) -> Dict: '''simple docstring''' A: int = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: A: List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Dict = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] A: Dict = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: Any = [tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) for seq in encoding['''input_ids''']] # fmt: off A: Any = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on A: Optional[int] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , SCREAMING_SNAKE_CASE_ ) for expected, decoded in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : int ) -> Optional[Any]: '''simple docstring''' A: List[Any] = n A: Tuple = [None] * self.n A: Optional[Any] = 0 # index of the first element A: Optional[int] = 0 A: List[Any] = 0 def __len__( self : Tuple ) -> int: '''simple docstring''' return self.size def _snake_case ( self : Union[str, Any] ) -> bool: '''simple docstring''' return self.size == 0 def _snake_case ( self : str ) -> int: '''simple docstring''' return False if self.is_empty() else self.array[self.front] def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str ) -> List[Any]: '''simple docstring''' if self.size >= self.n: raise Exception('''QUEUE IS FULL''' ) A: Optional[int] = data A: str = (self.rear + 1) % self.n self.size += 1 return self def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self.size == 0: raise Exception('''UNDERFLOW''' ) A: int = self.array[self.front] A: Union[str, Any] = None A: Tuple = (self.front + 1) % self.n self.size -= 1 return temp
350
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] , 1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
334
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
351
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } UpperCamelCase = { '''camembert-base''': 512, } UpperCamelCase = '''▁''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : str = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : int = CamembertTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : str="<s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE_ : List[Any]="</s>" , SCREAMING_SNAKE_CASE_ : int="<s>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<unk>" , SCREAMING_SNAKE_CASE_ : str="<pad>" , SCREAMING_SNAKE_CASE_ : List[str]="<mask>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , **SCREAMING_SNAKE_CASE_ : Any , ) -> Any: '''simple docstring''' A: Tuple = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Any = vocab_file A: Any = False if not self.vocab_file else True def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''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: List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: List[str] = [self.sep_token_id] A: Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return A: Dict = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
334
0
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) UpperCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE( __lowercase ) -> Union[str, Any]: A = git.Repo(search_parent_directories=__lowercase ) A = { '''repo_id''': str(__lowercase ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(__lowercase , '''git_log.json''' ) , '''w''' ) as f: json.dump(__lowercase , __lowercase , indent=4 ) def SCREAMING_SNAKE_CASE( __lowercase ) -> int: if params.n_gpu <= 0: A = 0 A = -1 A = True A = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 A = int(os.environ['''WORLD_SIZE'''] ) A = int(os.environ['''N_GPU_NODE'''] ) A = int(os.environ['''RANK'''] ) # number of nodes / node ID A = params.world_size // params.n_gpu_per_node A = params.global_rank // params.n_gpu_per_node A = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 A = 1 A = 0 A = 0 A = 0 A = 1 A = 1 A = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode A = params.node_id == 0 and params.local_rank == 0 A = params.n_nodes > 1 # summary A = F"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def SCREAMING_SNAKE_CASE( __lowercase ) -> Dict: np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
352
'''simple docstring''' import os from distutils.util import strtobool def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[Any]: for e in env_keys: A: Dict = int(os.environ.get(__lowercase , -1 ) ) if val >= 0: return val return default def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=False ) -> List[str]: A: str = os.environ.get(__lowercase , str(__lowercase ) ) return strtobool(__lowercase ) == 1 # As its name indicates `strtobool` actually returns an int... def SCREAMING_SNAKE_CASE( __lowercase , __lowercase="no" ) -> str: A: Optional[int] = os.environ.get(__lowercase , str(__lowercase ) ) return value
334
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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''google/vit-base-patch16-224''': '''https://huggingface.co/vit-base-patch16-224/resolve/main/config.json''', # See all ViT models at https://huggingface.co/models?filter=vit } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = """vit""" def __init__( self : Any , SCREAMING_SNAKE_CASE_ : Tuple=7_68 , SCREAMING_SNAKE_CASE_ : Optional[int]=12 , SCREAMING_SNAKE_CASE_ : Dict=12 , SCREAMING_SNAKE_CASE_ : List[Any]=30_72 , SCREAMING_SNAKE_CASE_ : Tuple="gelu" , SCREAMING_SNAKE_CASE_ : int=0.0 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.0 , SCREAMING_SNAKE_CASE_ : List[str]=0.02 , SCREAMING_SNAKE_CASE_ : List[str]=1E-12 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2_24 , SCREAMING_SNAKE_CASE_ : List[Any]=16 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : int=16 , **SCREAMING_SNAKE_CASE_ : Union[str, Any] , ) -> Dict: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) A: Any = hidden_size A: List[Any] = num_hidden_layers A: str = num_attention_heads A: str = intermediate_size A: Union[str, Any] = hidden_act A: int = hidden_dropout_prob A: Optional[int] = attention_probs_dropout_prob A: List[Any] = initializer_range A: Optional[int] = layer_norm_eps A: Dict = image_size A: Union[str, Any] = patch_size A: Any = num_channels A: List[str] = qkv_bias A: Tuple = encoder_stride class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = version.parse("""1.11""" ) @property def _snake_case ( self : Any ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def _snake_case ( self : List[str] ) -> float: '''simple docstring''' return 1E-4
353
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() UpperCamelCase = logging.get_logger('''transformers.models.encodec''') UpperCamelCase = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } UpperCamelCase = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } UpperCamelCase = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } UpperCamelCase = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } UpperCamelCase = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } UpperCamelCase = [] UpperCamelCase = [] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: for attribute in key.split('''.''' ): A: Union[str, Any] = getattr(__lowercase , __lowercase ) if weight_type is not None: A: Tuple = getattr(__lowercase , __lowercase ).shape else: A: str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": A: Dict = value elif weight_type == "weight_g": A: Tuple = value elif weight_type == "weight_v": A: Any = value elif weight_type == "bias": A: str = value elif weight_type == "running_mean": A: List[Any] = value elif weight_type == "running_var": A: Dict = value elif weight_type == "num_batches_tracked": A: List[str] = value elif weight_type == "weight_ih_l0": A: Dict = value elif weight_type == "weight_hh_l0": A: Optional[int] = value elif weight_type == "bias_ih_l0": A: List[Any] = value elif weight_type == "bias_hh_l0": A: str = value elif weight_type == "weight_ih_l1": A: Optional[int] = value elif weight_type == "weight_hh_l1": A: int = value elif weight_type == "bias_ih_l1": A: Optional[Any] = value elif weight_type == "bias_hh_l1": A: str = value else: A: Optional[int] = value logger.info(F"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Optional[Any]: for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: A , A: Any = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Tuple: A: Any = [] if model_name == "encodec_24khz" or "encodec_32khz": A: List[str] = MAPPING_24K elif model_name == "encodec_48khz": A: List[Any] = MAPPING_48K else: raise ValueError(F"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(__lowercase , __lowercase ): logger.info(F"""{name} was ignored""" ) continue A: Optional[int] = False for key, mapped_key in MAPPING.items(): if "*" in key: A , A: Optional[int] = key.split('''.*.''' ) if prefix in name and suffix in name: A: str = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('''embed''' ) and name.endswith('''embed_avg''' ): continue A: Optional[Any] = True if "*" in mapped_key: A: Any = name.split(__lowercase )[0].split('''.''' )[-2] A: Tuple = mapped_key.replace('''*''' , __lowercase ) if "weight_g" in name: A: str = '''weight_g''' elif "weight_v" in name: A: List[Any] = '''weight_v''' elif "weight_ih_l0" in name: A: Dict = '''weight_ih_l0''' elif "weight_hh_l0" in name: A: int = '''weight_hh_l0''' elif "bias_ih_l0" in name: A: Union[str, Any] = '''bias_ih_l0''' elif "bias_hh_l0" in name: A: Tuple = '''bias_hh_l0''' elif "weight_ih_l1" in name: A: int = '''weight_ih_l1''' elif "weight_hh_l1" in name: A: Optional[Any] = '''weight_hh_l1''' elif "bias_ih_l1" in name: A: Dict = '''bias_ih_l1''' elif "bias_hh_l1" in name: A: str = '''bias_hh_l1''' elif "bias" in name: A: Union[str, Any] = '''bias''' elif "weight" in name: A: Dict = '''weight''' elif "running_mean" in name: A: Tuple = '''running_mean''' elif "running_var" in name: A: Any = '''running_var''' elif "num_batches_tracked" in name: A: str = '''num_batches_tracked''' else: A: Tuple = None set_recursively(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) continue if not is_used: unused_weights.append(__lowercase ) logger.warning(F"""Unused weights: {unused_weights}""" ) @torch.no_grad() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase=None , __lowercase=None , ) -> Dict: if config_path is not None: A: Tuple = EncodecConfig.from_pretrained(__lowercase ) else: A: Union[str, Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": A: Union[str, Any] = [8, 5, 4, 4] A: Dict = [2.2] A: List[Any] = 6_4 A: Optional[Any] = 3_2_0_0_0 A: List[Any] = 2_0_4_8 A: Optional[Any] = False A: int = False A: Union[str, Any] = False elif model_name == "encodec_48khz": A: Optional[int] = [8, 5, 4, 2] A: List[Any] = [3.0, 6.0, 1_2.0, 2_4.0] A: List[Any] = 4_8_0_0_0 A: int = 2 A: List[Any] = False A: Any = '''time_group_norm''' A: Optional[Any] = True A: Any = 1.0 A: Any = 0.0_1 else: raise ValueError(F"""Unknown model name: {model_name}""" ) A: str = EncodecModel(__lowercase ) A: Optional[Any] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__lowercase ) A: Union[str, Any] = torch.load(__lowercase ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights A: Optional[int] = original_checkpoint['''best_state'''] recursively_load_weights(__lowercase , __lowercase , __lowercase ) model.save_pretrained(__lowercase ) if repo_id: print('''Pushing to the hub...''' ) feature_extractor.push_to_hub(__lowercase ) model.push_to_hub(__lowercase ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) UpperCamelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
334
0
'''simple docstring''' import os from pathlib import Path def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Any: A: Dict = { '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''Машинное обучение - это здорово, не так ли?''', '''de''': '''Maschinelles Lernen ist großartig, oder?''', } # BLUE scores as follows: # "pair": [fairseq, transformers] A: Tuple = { '''ru-en''': ['''[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)''', '''39.20'''], '''en-ru''': ['''[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)''', '''33.47'''], '''en-de''': ['''[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)''', '''42.83'''], '''de-en''': ['''[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)''', '''41.35'''], } A: str = F"""{src_lang}-{tgt_lang}""" A: Optional[Any] = F""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR's WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) """ os.makedirs(__lowercase , exist_ok=__lowercase ) A: Dict = os.path.join(__lowercase , '''README.md''' ) print(F"""Generating {path}""" ) with open(__lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(__lowercase ) # make sure we are under the root of the project UpperCamelCase = Path(__file__).resolve().parent.parent.parent UpperCamelCase = repo_dir / '''model_cards''' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: UpperCamelCase , UpperCamelCase , UpperCamelCase = model_name.split('''-''') UpperCamelCase = model_cards_dir / '''facebook''' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
354
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
355
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for data in source_data: for i, el in enumerate(__lowercase ): if len(__lowercase ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__lowercase ) ) return data_lists def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for dlist, weight in zip(__lowercase , __lowercase ): A: List[str] = min(__lowercase ) A: Union[str, Any] = max(__lowercase ) A: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: A: List[str] = F"""Invalid weight of {weight:f} provided""" raise ValueError(__lowercase ) score_lists.append(__lowercase ) return score_lists def SCREAMING_SNAKE_CASE( __lowercase ) -> list[float]: A: list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__lowercase ): A: str = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: Any = get_data(__lowercase ) A: str = calculate_each_score(__lowercase , __lowercase ) A: int = generate_final_scores(__lowercase ) # append scores to source data for i, ele in enumerate(__lowercase ): source_data[i].append(__lowercase ) return source_data
334
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : torch.FloatTensor class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE_ : int = 6_55_36 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : str = "fourier" , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , SCREAMING_SNAKE_CASE_ : Tuple[str] = "UNetMidBlock1D" , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : Tuple[int] = (32, 32, 64) , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : int = 8 , SCREAMING_SNAKE_CASE_ : int = 1 , SCREAMING_SNAKE_CASE_ : bool = False , ) -> Tuple: '''simple docstring''' super().__init__() A: Optional[Any] = sample_size # time if time_embedding_type == "fourier": A: Tuple = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=SCREAMING_SNAKE_CASE_ , log=SCREAMING_SNAKE_CASE_ , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ ) A: List[str] = 2 * block_out_channels[0] elif time_embedding_type == "positional": A: str = Timesteps( block_out_channels[0] , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ , downscale_freq_shift=SCREAMING_SNAKE_CASE_ ) A: Any = block_out_channels[0] if use_timestep_embedding: A: Optional[Any] = block_out_channels[0] * 4 A: List[Any] = TimestepEmbedding( in_channels=SCREAMING_SNAKE_CASE_ , time_embed_dim=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , out_dim=block_out_channels[0] , ) A: Optional[Any] = nn.ModuleList([] ) A: str = None A: str = nn.ModuleList([] ) A: Tuple = None # down A: Any = in_channels for i, down_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = output_channel A: List[Any] = block_out_channels[i] if i == 0: input_channel += extra_in_channels A: List[Any] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[int] = get_down_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(SCREAMING_SNAKE_CASE_ ) # mid A: Union[str, Any] = get_mid_block( SCREAMING_SNAKE_CASE_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=SCREAMING_SNAKE_CASE_ , add_downsample=SCREAMING_SNAKE_CASE_ , ) # up A: Optional[Any] = list(reversed(SCREAMING_SNAKE_CASE_ ) ) A: List[str] = reversed_block_out_channels[0] if out_block_type is None: A: int = out_channels else: A: Union[str, Any] = block_out_channels[0] for i, up_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: List[Any] = output_channel A: int = ( reversed_block_out_channels[i + 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 else final_upsample_channels ) A: Optional[int] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[Any] = get_up_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(SCREAMING_SNAKE_CASE_ ) A: Any = output_channel # out A: List[str] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) A: Optional[int] = get_out_block( out_block_type=SCREAMING_SNAKE_CASE_ , num_groups_out=SCREAMING_SNAKE_CASE_ , embed_dim=block_out_channels[0] , out_channels=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , fc_dim=block_out_channels[-1] // 4 , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : torch.FloatTensor , SCREAMING_SNAKE_CASE_ : Union[torch.Tensor, float, int] , SCREAMING_SNAKE_CASE_ : bool = True , ) -> Union[UNetaDOutput, Tuple]: '''simple docstring''' A: Any = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(SCREAMING_SNAKE_CASE_ ) and len(timesteps.shape ) == 0: A: List[str] = timesteps[None].to(sample.device ) A: int = self.time_proj(SCREAMING_SNAKE_CASE_ ) if self.config.use_timestep_embedding: A: List[Any] = self.time_mlp(SCREAMING_SNAKE_CASE_ ) else: A: str = timestep_embed[..., None] A: Union[str, Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) A: Tuple = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down A: List[str] = () for downsample_block in self.down_blocks: A: Optional[int] = downsample_block(hidden_states=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: A: Dict = self.mid_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): A: List[Any] = down_block_res_samples[-1:] A: List[str] = down_block_res_samples[:-1] A: Optional[int] = upsample_block(SCREAMING_SNAKE_CASE_ , res_hidden_states_tuple=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) # 5. post-process if self.out_block: A: Any = self.out_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=SCREAMING_SNAKE_CASE_ )
356
'''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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = DPRContextEncoderTokenizer class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Dict = VOCAB_FILES_NAMES UpperCamelCase_ : List[str] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Tuple = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Optional[int] = DPRQuestionEncoderTokenizer UpperCamelCase = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) UpperCamelCase = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) UpperCamelCase = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ : '''simple docstring''' def __call__( self : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchEncoding: '''simple docstring''' if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) elif titles is None or texts is None: A: Union[str, Any] = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = titles if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [titles] A: Optional[Any] = texts if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [texts] A: str = len(SCREAMING_SNAKE_CASE_ ) A: List[Any] = questions if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [questions] * n_passages assert len(SCREAMING_SNAKE_CASE_ ) == len( SCREAMING_SNAKE_CASE_ ), f"""There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE_ )} titles and {len(SCREAMING_SNAKE_CASE_ )} texts.""" A: Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: Dict = super().__call__(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: str = { '''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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] } if return_attention_mask is not False: A: Union[str, Any] = [] 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: Optional[Any] = attention_mask return self.pad(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : BatchEncoding , SCREAMING_SNAKE_CASE_ : DPRReaderOutput , SCREAMING_SNAKE_CASE_ : int = 16 , SCREAMING_SNAKE_CASE_ : int = 64 , SCREAMING_SNAKE_CASE_ : int = 4 , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Any = reader_input['''input_ids'''] A , A , A: str = reader_output[:3] A: str = len(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = sorted(range(SCREAMING_SNAKE_CASE_ ) , reverse=SCREAMING_SNAKE_CASE_ , key=relevance_logits.__getitem__ ) A: List[DPRReaderOutput] = [] for doc_id in sorted_docs: A: List[str] = 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: Union[str, Any] = sequence_ids.index(self.pad_token_id ) else: A: int = len(SCREAMING_SNAKE_CASE_ ) A: Dict = 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=SCREAMING_SNAKE_CASE_ , top_spans=SCREAMING_SNAKE_CASE_ , ) 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=SCREAMING_SNAKE_CASE_ , start_index=SCREAMING_SNAKE_CASE_ , end_index=SCREAMING_SNAKE_CASE_ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE_ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Union[str, Any] = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE_ ): 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: Any = sorted(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : x[1] , reverse=SCREAMING_SNAKE_CASE_ ) A: Dict = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]""" A: int = 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(SCREAMING_SNAKE_CASE_ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] = READER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = READER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : Optional[Any] = DPRReaderTokenizer
334
0
'''simple docstring''' import inspect import unittest from math import floor from transformers import CvtConfig 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 transformers import CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def _snake_case ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' A: Any = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''embed_dim''' ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''num_heads''' ) ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[Any]=13 , SCREAMING_SNAKE_CASE_ : List[str]=64 , SCREAMING_SNAKE_CASE_ : List[str]=3 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=[16, 48, 96] , SCREAMING_SNAKE_CASE_ : str=[1, 3, 6] , SCREAMING_SNAKE_CASE_ : Any=[1, 2, 10] , SCREAMING_SNAKE_CASE_ : Tuple=[7, 3, 3] , SCREAMING_SNAKE_CASE_ : Dict=[4, 2, 2] , SCREAMING_SNAKE_CASE_ : Optional[Any]=[2, 1, 1] , SCREAMING_SNAKE_CASE_ : Union[str, Any]=[2, 2, 2] , SCREAMING_SNAKE_CASE_ : Optional[int]=[False, False, True] , SCREAMING_SNAKE_CASE_ : str=[0.0, 0.0, 0.0] , SCREAMING_SNAKE_CASE_ : Tuple=0.02 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1E-12 , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2 , ) -> str: '''simple docstring''' A: Optional[int] = parent A: Any = batch_size A: Union[str, Any] = image_size A: int = patch_sizes A: Optional[int] = patch_stride A: Any = patch_padding A: int = is_training A: Union[str, Any] = use_labels A: Union[str, Any] = num_labels A: Optional[int] = num_channels A: List[Any] = embed_dim A: Optional[int] = num_heads A: int = stride_kv A: Tuple = depth A: Dict = cls_token A: Tuple = attention_drop_rate A: List[str] = initializer_range A: List[Any] = layer_norm_eps def _snake_case ( self : str ) -> List[Any]: '''simple docstring''' A: Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A: List[Any] = None if self.use_labels: A: str = ids_tensor([self.batch_size] , self.num_labels ) A: Any = self.get_config() return config, pixel_values, labels def _snake_case ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Any: '''simple docstring''' A: List[str] = CvtModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() A: int = model(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = (self.image_size, self.image_size) A: Tuple = image_size[0], image_size[1] for i in range(len(self.depth ) ): A: Tuple = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) A: int = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[str] ) -> int: '''simple docstring''' A: List[str] = self.num_labels A: Dict = CvtForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() A: Tuple = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Union[str, Any] ) -> str: '''simple docstring''' A: Dict = self.prepare_config_and_inputs() A: Union[str, Any] = config_and_inputs A: int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = (CvtModel, CvtForImageClassification) if is_torch_available() else () UpperCamelCase_ : Union[str, Any] = ( {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification} if is_torch_available() else {} ) UpperCamelCase_ : Dict = False UpperCamelCase_ : List[Any] = False UpperCamelCase_ : List[Any] = False UpperCamelCase_ : Dict = False UpperCamelCase_ : Any = False def _snake_case ( self : Optional[int] ) -> List[Any]: '''simple docstring''' A: Dict = CvtModelTester(self ) A: str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def _snake_case ( self : Optional[Any] ) -> Tuple: '''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 _snake_case ( self : Tuple ) -> Tuple: '''simple docstring''' return @unittest.skip(reason='''Cvt does not output attentions''' ) def _snake_case ( self : Dict ) -> Tuple: '''simple docstring''' pass @unittest.skip(reason='''Cvt does not use inputs_embeds''' ) def _snake_case ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason='''Cvt does not support input and output embeddings''' ) def _snake_case ( self : int ) -> Any: '''simple docstring''' pass def _snake_case ( self : Any ) -> List[Any]: '''simple docstring''' A: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A: Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) A: int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A: str = [*signature.parameters.keys()] A: Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Optional[Any] ) -> Any: '''simple docstring''' A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Dict: '''simple docstring''' def check_hidden_states_output(SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int ): A: List[str] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): A: str = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) A: Optional[Any] = outputs.hidden_states A: Dict = len(self.model_tester.depth ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) A: Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A: List[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A: Dict = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple ) -> List[Any]: '''simple docstring''' A: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _snake_case ( self : Optional[int] ) -> Any: '''simple docstring''' pass @slow def _snake_case ( self : Dict ) -> Dict: '''simple docstring''' for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A: List[Any] = CvtModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE( ) -> List[Any]: A: Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Tuple ) -> str: '''simple docstring''' return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : str ) -> Any: '''simple docstring''' A: Optional[int] = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(SCREAMING_SNAKE_CASE_ ) A: List[Any] = self.default_image_processor A: List[str] = prepare_img() A: Tuple = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): A: Tuple = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits A: Tuple = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) A: int = torch.tensor([0.9285, 0.9015, -0.3150] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
357
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
358
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' pass class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> None: '''simple docstring''' A: Any = data A: Node | None = None def __iter__( self : Optional[int] ) -> List[str]: '''simple docstring''' A: List[str] = self A: Dict = [] while node: if node in visited: raise ContainsLoopError visited.append(SCREAMING_SNAKE_CASE_ ) yield node.data A: str = node.next_node @property def _snake_case ( self : List[str] ) -> bool: '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": UpperCamelCase = Node(1) UpperCamelCase = Node(2) UpperCamelCase = Node(3) UpperCamelCase = Node(4) print(root_node.has_loop) # False UpperCamelCase = root_node.next_node print(root_node.has_loop) # True UpperCamelCase = Node(5) UpperCamelCase = Node(6) UpperCamelCase = Node(5) UpperCamelCase = Node(6) print(root_node.has_loop) # False UpperCamelCase = Node(1) print(root_node.has_loop) # False
334
0
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : List[nn.Module] = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : list = field(default_factory=UpperCAmelCase_ ) def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tensor , SCREAMING_SNAKE_CASE_ : Tensor ) -> int: '''simple docstring''' A: List[str] = len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE_ , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE_ ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tensor ) -> Dict: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE_ ) [x.remove() for x in self.handles] return self @property def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' return list(filter(lambda SCREAMING_SNAKE_CASE_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : nn.Module UpperCamelCase_ : int = 0 UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) def __call__( self : Any , SCREAMING_SNAKE_CASE_ : Tensor ) -> Optional[Any]: '''simple docstring''' A: Dict = Tracker(self.dest )(SCREAMING_SNAKE_CASE_ ).parametrized A: Tuple = Tracker(self.src )(SCREAMING_SNAKE_CASE_ ).parametrized A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.src_skip , SCREAMING_SNAKE_CASE_ ) ) A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.dest_skip , SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise Exception( f"""Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE_ )} operations while""" f""" destination module has {len(SCREAMING_SNAKE_CASE_ )}.""" ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = True ) -> Any: print(F"""Converting {name}...""" ) with torch.no_grad(): A: Union[str, Any] = timm.create_model(__lowercase , pretrained=__lowercase ).eval() A: List[str] = ResNetForImageClassification(__lowercase ).eval() A: int = ModuleTransfer(src=__lowercase , dest=__lowercase ) A: List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(__lowercase ) assert torch.allclose(from_model(__lowercase ) , our_model(__lowercase ).logits ), "The model logits don't match the original one." A: str = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(__lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=__lowercase , ) # we can use the convnext one A: Any = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=__lowercase , ) print(F"""Pushed {checkpoint_name}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = None , __lowercase = True ) -> List[Any]: A: Union[str, Any] = '''imagenet-1k-id2label.json''' A: Union[str, Any] = 1_0_0_0 A: Optional[int] = (1, num_labels) A: Dict = '''huggingface/label-files''' A: Any = num_labels A: Union[str, Any] = json.load(open(hf_hub_download(__lowercase , __lowercase , repo_type='''dataset''' ) , '''r''' ) ) A: Optional[int] = {int(__lowercase ): v for k, v in idalabel.items()} A: Optional[int] = idalabel A: List[str] = {v: k for k, v in idalabel.items()} A: str = partial(__lowercase , num_labels=__lowercase , idalabel=__lowercase , labelaid=__lowercase ) A: Optional[Any] = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(__lowercase , names_to_config[model_name] , __lowercase , __lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowercase , __lowercase , __lowercase , __lowercase ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
359
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE( __lowercase = 4 ) -> list[list[int]]: A: Tuple = abs(__lowercase ) or 4 return [[1 + x + y * row_size for x in range(__lowercase )] for y in range(__lowercase )] def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(transpose(__lowercase ) ) # OR.. transpose(reverse_column(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(reverse_column(__lowercase ) ) # OR.. reverse_column(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_column(transpose(__lowercase ) ) # OR.. transpose(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Union[str, Any] = [list(__lowercase ) for x in zip(*__lowercase )] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[int] = matrix[::-1] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[Any] = [x[::-1] for x in matrix] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> None: for i in matrix: print(*__lowercase ) if __name__ == "__main__": UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
334
0
'''simple docstring''' import unittest import numpy as np def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = None , ) -> np.ndarray: A: List[str] = np.shape(__lowercase ) A: str = np.shape(__lowercase ) A: Tuple = np.shape(__lowercase ) if shape_a[0] != shape_b[0]: A: Any = ( '''Expected the same number of rows for A and B. ''' F"""Instead found A of size {shape_a} and B of size {shape_b}""" ) raise ValueError(__lowercase ) if shape_b[1] != shape_c[1]: A: str = ( '''Expected the same number of columns for B and C. ''' F"""Instead found B of size {shape_b} and C of size {shape_c}""" ) raise ValueError(__lowercase ) A: Dict = pseudo_inv if a_inv is None: try: A: int = np.linalg.inv(__lowercase ) except np.linalg.LinAlgError: raise ValueError( '''Input matrix A is not invertible. Cannot compute Schur complement.''' ) return mat_c - mat_b.T @ a_inv @ mat_b class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ) -> None: '''simple docstring''' A: str = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) A: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) A: Any = np.array([[2, 1], [6, 3]] ) A: str = schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Any = np.block([[a, b], [b.T, c]] ) A: Any = np.linalg.det(SCREAMING_SNAKE_CASE_ ) A: str = np.linalg.det(SCREAMING_SNAKE_CASE_ ) A: str = np.linalg.det(SCREAMING_SNAKE_CASE_ ) self.assertAlmostEqual(SCREAMING_SNAKE_CASE_ , det_a * det_s ) def _snake_case ( self : str ) -> None: '''simple docstring''' A: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) A: Tuple = np.array([[0, 3], [3, 0], [2, 3]] ) A: Union[str, Any] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Any ) -> None: '''simple docstring''' A: str = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) A: int = np.array([[0, 3], [3, 0], [2, 3]] ) A: Optional[int] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
360
'''simple docstring''' from __future__ import annotations import numpy as np def SCREAMING_SNAKE_CASE( __lowercase ) -> Dict: return np.maximum(0 , __lowercase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
334
0
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE_ : Dict , **SCREAMING_SNAKE_CASE_ : int ) -> None: '''simple docstring''' warnings.warn( '''The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use FlavaImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
361
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() UpperCamelCase = logging.get_logger('''transformers.models.encodec''') UpperCamelCase = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } UpperCamelCase = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } UpperCamelCase = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } UpperCamelCase = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } UpperCamelCase = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } UpperCamelCase = [] UpperCamelCase = [] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: for attribute in key.split('''.''' ): A: Union[str, Any] = getattr(__lowercase , __lowercase ) if weight_type is not None: A: Tuple = getattr(__lowercase , __lowercase ).shape else: A: str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": A: Dict = value elif weight_type == "weight_g": A: Tuple = value elif weight_type == "weight_v": A: Any = value elif weight_type == "bias": A: str = value elif weight_type == "running_mean": A: List[Any] = value elif weight_type == "running_var": A: Dict = value elif weight_type == "num_batches_tracked": A: List[str] = value elif weight_type == "weight_ih_l0": A: Dict = value elif weight_type == "weight_hh_l0": A: Optional[int] = value elif weight_type == "bias_ih_l0": A: List[Any] = value elif weight_type == "bias_hh_l0": A: str = value elif weight_type == "weight_ih_l1": A: Optional[int] = value elif weight_type == "weight_hh_l1": A: int = value elif weight_type == "bias_ih_l1": A: Optional[Any] = value elif weight_type == "bias_hh_l1": A: str = value else: A: Optional[int] = value logger.info(F"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Optional[Any]: for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: A: Any = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Tuple: A: Any = [] if model_name == "encodec_24khz" or "encodec_32khz": A: List[str] = MAPPING_24K elif model_name == "encodec_48khz": A: List[Any] = MAPPING_48K else: raise ValueError(F"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(__lowercase , __lowercase ): logger.info(F"""{name} was ignored""" ) continue A: Optional[int] = False for key, mapped_key in MAPPING.items(): if "*" in key: A: Optional[int] = key.split('''.*.''' ) if prefix in name and suffix in name: A: str = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('''embed''' ) and name.endswith('''embed_avg''' ): continue A: Optional[Any] = True if "*" in mapped_key: A: Any = name.split(__lowercase )[0].split('''.''' )[-2] A: Tuple = mapped_key.replace('''*''' , __lowercase ) if "weight_g" in name: A: str = '''weight_g''' elif "weight_v" in name: A: List[Any] = '''weight_v''' elif "weight_ih_l0" in name: A: Dict = '''weight_ih_l0''' elif "weight_hh_l0" in name: A: int = '''weight_hh_l0''' elif "bias_ih_l0" in name: A: Union[str, Any] = '''bias_ih_l0''' elif "bias_hh_l0" in name: A: Tuple = '''bias_hh_l0''' elif "weight_ih_l1" in name: A: int = '''weight_ih_l1''' elif "weight_hh_l1" in name: A: Optional[Any] = '''weight_hh_l1''' elif "bias_ih_l1" in name: A: Dict = '''bias_ih_l1''' elif "bias_hh_l1" in name: A: str = '''bias_hh_l1''' elif "bias" in name: A: Union[str, Any] = '''bias''' elif "weight" in name: A: Dict = '''weight''' elif "running_mean" in name: A: Tuple = '''running_mean''' elif "running_var" in name: A: Any = '''running_var''' elif "num_batches_tracked" in name: A: str = '''num_batches_tracked''' else: A: Tuple = None set_recursively(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) continue if not is_used: unused_weights.append(__lowercase ) logger.warning(F"""Unused weights: {unused_weights}""" ) @torch.no_grad() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase=None , __lowercase=None , ) -> Dict: if config_path is not None: A: Tuple = EncodecConfig.from_pretrained(__lowercase ) else: A: Union[str, Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": A: Union[str, Any] = [8, 5, 4, 4] A: Dict = [2.2] A: List[Any] = 6_4 A: Optional[Any] = 3_2_0_0_0 A: List[Any] = 2_0_4_8 A: Optional[Any] = False A: int = False A: Union[str, Any] = False elif model_name == "encodec_48khz": A: Optional[int] = [8, 5, 4, 2] A: List[Any] = [3.0, 6.0, 1_2.0, 2_4.0] A: List[Any] = 4_8_0_0_0 A: int = 2 A: List[Any] = False A: Any = '''time_group_norm''' A: Optional[Any] = True A: Any = 1.0 A: Any = 0.0_1 else: raise ValueError(F"""Unknown model name: {model_name}""" ) A: str = EncodecModel(__lowercase ) A: Optional[Any] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__lowercase ) A: Union[str, Any] = torch.load(__lowercase ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights A: Optional[int] = original_checkpoint['''best_state'''] recursively_load_weights(__lowercase , __lowercase , __lowercase ) model.save_pretrained(__lowercase ) if repo_id: print('''Pushing to the hub...''' ) feature_extractor.push_to_hub(__lowercase ) model.push_to_hub(__lowercase ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) UpperCamelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
362
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
334
0
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = ["""image_processor""", """tokenizer"""] UpperCamelCase_ : Any = """ViTImageProcessor""" UpperCamelCase_ : Optional[int] = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : Tuple=None , **SCREAMING_SNAKE_CASE_ : str ) -> Dict: '''simple docstring''' A: Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , SCREAMING_SNAKE_CASE_ , ) A: List[str] = kwargs.pop('''feature_extractor''' ) A: Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __call__( self : Dict , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : Any=None , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Union[str, Any]: '''simple docstring''' if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''' ) if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' ) if text is not None: A: Union[str, Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if visual_prompt is not None: A: List[str] = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if images is not None: A: str = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if visual_prompt is not None and images is not None: A: Any = { '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: A: List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: A: Union[str, Any] = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_ ) , tensor_type=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , *SCREAMING_SNAKE_CASE_ : int , **SCREAMING_SNAKE_CASE_ : Tuple ) -> Tuple: '''simple docstring''' return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , *SCREAMING_SNAKE_CASE_ : List[Any] , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def _snake_case ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , SCREAMING_SNAKE_CASE_ , ) return self.image_processor_class @property def _snake_case ( self : str ) -> Dict: '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , SCREAMING_SNAKE_CASE_ , ) return self.image_processor
363
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : torch.FloatTensor class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE_ : int = 6_55_36 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : str = "fourier" , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , SCREAMING_SNAKE_CASE_ : Tuple[str] = "UNetMidBlock1D" , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : Tuple[int] = (32, 32, 64) , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : int = 8 , SCREAMING_SNAKE_CASE_ : int = 1 , SCREAMING_SNAKE_CASE_ : bool = False , ) -> Tuple: '''simple docstring''' super().__init__() A: Optional[Any] = sample_size # time if time_embedding_type == "fourier": A: Tuple = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=SCREAMING_SNAKE_CASE_ , log=SCREAMING_SNAKE_CASE_ , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ ) A: List[str] = 2 * block_out_channels[0] elif time_embedding_type == "positional": A: str = Timesteps( block_out_channels[0] , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ , downscale_freq_shift=SCREAMING_SNAKE_CASE_ ) A: Any = block_out_channels[0] if use_timestep_embedding: A: Optional[Any] = block_out_channels[0] * 4 A: List[Any] = TimestepEmbedding( in_channels=SCREAMING_SNAKE_CASE_ , time_embed_dim=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , out_dim=block_out_channels[0] , ) A: Optional[Any] = nn.ModuleList([] ) A: str = None A: str = nn.ModuleList([] ) A: Tuple = None # down A: Any = in_channels for i, down_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = output_channel A: List[Any] = block_out_channels[i] if i == 0: input_channel += extra_in_channels A: List[Any] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[int] = get_down_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(SCREAMING_SNAKE_CASE_ ) # mid A: Union[str, Any] = get_mid_block( SCREAMING_SNAKE_CASE_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=SCREAMING_SNAKE_CASE_ , add_downsample=SCREAMING_SNAKE_CASE_ , ) # up A: Optional[Any] = list(reversed(SCREAMING_SNAKE_CASE_ ) ) A: List[str] = reversed_block_out_channels[0] if out_block_type is None: A: int = out_channels else: A: Union[str, Any] = block_out_channels[0] for i, up_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: List[Any] = output_channel A: int = ( reversed_block_out_channels[i + 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 else final_upsample_channels ) A: Optional[int] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[Any] = get_up_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(SCREAMING_SNAKE_CASE_ ) A: Any = output_channel # out A: List[str] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) A: Optional[int] = get_out_block( out_block_type=SCREAMING_SNAKE_CASE_ , num_groups_out=SCREAMING_SNAKE_CASE_ , embed_dim=block_out_channels[0] , out_channels=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , fc_dim=block_out_channels[-1] // 4 , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : torch.FloatTensor , SCREAMING_SNAKE_CASE_ : Union[torch.Tensor, float, int] , SCREAMING_SNAKE_CASE_ : bool = True , ) -> Union[UNetaDOutput, Tuple]: '''simple docstring''' A: Any = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(SCREAMING_SNAKE_CASE_ ) and len(timesteps.shape ) == 0: A: List[str] = timesteps[None].to(sample.device ) A: int = self.time_proj(SCREAMING_SNAKE_CASE_ ) if self.config.use_timestep_embedding: A: List[Any] = self.time_mlp(SCREAMING_SNAKE_CASE_ ) else: A: str = timestep_embed[..., None] A: Union[str, Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) A: Tuple = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down A: List[str] = () for downsample_block in self.down_blocks: A , A: Optional[int] = downsample_block(hidden_states=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: A: Dict = self.mid_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): A: List[Any] = down_block_res_samples[-1:] A: List[str] = down_block_res_samples[:-1] A: Optional[int] = upsample_block(SCREAMING_SNAKE_CASE_ , res_hidden_states_tuple=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) # 5. post-process if self.out_block: A: Any = self.out_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=1_0 ) -> Tuple: A: List[Any] = [] for _ in range(__lowercase ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=1_0 ) -> Any: A: int = [] for step in range(__lowercase ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: A: Any = os.path.join(__lowercase , '''schedule.bin''' ) torch.save(scheduler.state_dict() , __lowercase ) A: Union[str, Any] = torch.load(__lowercase ) scheduler.load_state_dict(__lowercase ) return lrs @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for a, b in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , delta=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Optional[int]: '''simple docstring''' A: Tuple = torch.tensor([0.1, -0.2, -0.1] , requires_grad=SCREAMING_SNAKE_CASE_ ) A: str = torch.tensor([0.4, 0.2, -0.5] ) A: List[str] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping A: int = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(1_00 ): A: int = criterion(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def _snake_case ( self : int ) -> Dict: '''simple docstring''' A: List[Any] = torch.tensor([0.1, -0.2, -0.1] , requires_grad=SCREAMING_SNAKE_CASE_ ) A: List[str] = torch.tensor([0.4, 0.2, -0.5] ) A: int = nn.MSELoss() # No warmup, constant schedule, no gradient clipping A: List[Any] = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=SCREAMING_SNAKE_CASE_ , weight_decay=0.0 , relative_step=SCREAMING_SNAKE_CASE_ , scale_parameter=SCREAMING_SNAKE_CASE_ , warmup_init=SCREAMING_SNAKE_CASE_ , ) for _ in range(10_00 ): A: Dict = criterion(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = nn.Linear(50 , 50 ) if is_torch_available() else None UpperCamelCase_ : List[str] = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None UpperCamelCase_ : List[str] = 10 def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str]=None ) -> Dict: '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for a, b in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , delta=SCREAMING_SNAKE_CASE_ , msg=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[str] ) -> List[Any]: '''simple docstring''' A: Union[str, Any] = {'''num_warmup_steps''': 2, '''num_training_steps''': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) A: Optional[int] = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'''num_warmup_steps''': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, '''num_cycles''': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, '''power''': 2.0, '''lr_end''': 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'''num_warmup_steps''': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): A: Optional[Any] = data A: Any = scheduler_func(self.optimizer , **SCREAMING_SNAKE_CASE_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) A: int = unwrap_schedule(SCREAMING_SNAKE_CASE_ , self.num_steps ) self.assertListAlmostEqual( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tol=1E-2 , msg=f"""failed for {scheduler_func} in normal scheduler""" , ) A: Union[str, Any] = scheduler_func(self.optimizer , **SCREAMING_SNAKE_CASE_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(SCREAMING_SNAKE_CASE_ ) # wrap to test picklability of the schedule A: Any = unwrap_and_save_reload_schedule(SCREAMING_SNAKE_CASE_ , self.num_steps ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , msg=f"""failed for {scheduler_func} in save and reload""" ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict ) -> Optional[Any]: '''simple docstring''' A: Dict = fn def __call__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE_ : List[str] , **SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[int]: '''simple docstring''' return self.fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @classmethod def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Dict: '''simple docstring''' A: int = list(map(self , scheduler.lr_lambdas ) )
364
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , *SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Dict ) -> None: '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import logging import os from .state import PartialState class lowerCAmelCase_ ( logging.LoggerAdapter ): @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , *SCREAMING_SNAKE_CASE_ : List[Any] , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> Tuple: '''simple docstring''' if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) A: List[str] = kwargs.pop('''main_process_only''' , SCREAMING_SNAKE_CASE_ ) A: Dict = kwargs.pop('''in_order''' , SCREAMING_SNAKE_CASE_ ) if self.isEnabledFor(SCREAMING_SNAKE_CASE_ ): if self._should_log(SCREAMING_SNAKE_CASE_ ): A: str = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) elif in_order: A: Optional[Any] = PartialState() for i in range(state.num_processes ): if i == state.process_index: A: Optional[Any] = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) state.wait_for_everyone() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = None ) -> int: if log_level is None: A: Dict = os.environ.get('''ACCELERATE_LOG_LEVEL''' , __lowercase ) A: Tuple = logging.getLogger(__lowercase ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__lowercase , {} )
365
'''simple docstring''' from collections import deque class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> None: '''simple docstring''' A: Union[str, Any] = process_name # process name A: List[str] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time A: Dict = arrival_time A: Optional[Any] = burst_time # remaining burst time A: Any = 0 # total time of the process wait in ready queue A: Any = 0 # time from arrival time to completion time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int , ) -> None: '''simple docstring''' A: Dict = number_of_queues # time slice of queues that round robin algorithm applied A: int = time_slices # unfinished process is in this ready_queue A: Tuple = queue # current time A: int = current_time # finished process is in this sequence queue A: deque[Process] = deque() def _snake_case ( self : List[Any] ) -> list[str]: '''simple docstring''' A: str = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Optional[int] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Any = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: List[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> list[int]: '''simple docstring''' return [q.burst_time for q in queue] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Process ) -> int: '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> deque[Process]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE_ ) != 0: A: Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 A: Any = 0 # set the process's turnaround time because it is finished A: int = self.current_time - cp.arrival_time # set the completion time A: List[str] = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int ) -> tuple[deque[Process], deque[Process]]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE_ ) ): A: Dict = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time A: Optional[Any] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished A: int = 0 # set the finish time A: Union[str, Any] = self.current_time # update the process' turnaround time because it is finished A: Tuple = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _snake_case ( self : Optional[Any] ) -> deque[Process]: '''simple docstring''' for i in range(self.number_of_queues - 1 ): A , A: Optional[Any] = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])}) UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) UpperCamelCase = MLFQ(number_of_queues, time_slices, queue, 0) UpperCamelCase = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print completion times of processes(P1, P2, P3, P4) print( f'completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print sequence of finished processes print( f'sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}' )
334
0
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. UpperCamelCase = 10 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase ) -> int: for i in range(__lowercase , __lowercase ): if array[i] == target: return i return -1 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> int: A: str = 0 A: List[Any] = len(__lowercase ) while left <= right: if right - left < precision: return lin_search(__lowercase , __lowercase , __lowercase , __lowercase ) A: Dict = (left + right) // 3 + 1 A: Dict = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: A: Dict = one_third - 1 elif array[two_third] < target: A: List[str] = two_third + 1 else: A: Optional[Any] = one_third + 1 A: Optional[int] = two_third - 1 else: return -1 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase ) -> int: if left < right: if right - left < precision: return lin_search(__lowercase , __lowercase , __lowercase , __lowercase ) A: Dict = (left + right) // 3 + 1 A: str = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(__lowercase , one_third - 1 , __lowercase , __lowercase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , __lowercase , __lowercase , __lowercase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , __lowercase , __lowercase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase = input('''Enter numbers separated by comma:\n''').strip() UpperCamelCase = [int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." UpperCamelCase = int(input('''Enter the number to be found in the list:\n''').strip()) UpperCamelCase = ite_ternary_search(collection, target) UpperCamelCase = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'Iterative search: {target} found at positions: {resulta}') print(f'Recursive search: {target} found at positions: {resulta}') else: print('''Not found''')
366
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : List[nn.Module] = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : list = field(default_factory=UpperCAmelCase_ ) def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tensor , SCREAMING_SNAKE_CASE_ : Tensor ) -> int: '''simple docstring''' A: List[str] = len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE_ , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE_ ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tensor ) -> Dict: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE_ ) [x.remove() for x in self.handles] return self @property def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' return list(filter(lambda SCREAMING_SNAKE_CASE_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : nn.Module UpperCamelCase_ : int = 0 UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) def __call__( self : Any , SCREAMING_SNAKE_CASE_ : Tensor ) -> Optional[Any]: '''simple docstring''' A: Dict = Tracker(self.dest )(SCREAMING_SNAKE_CASE_ ).parametrized A: Tuple = Tracker(self.src )(SCREAMING_SNAKE_CASE_ ).parametrized A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.src_skip , SCREAMING_SNAKE_CASE_ ) ) A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.dest_skip , SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise Exception( f"""Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE_ )} operations while""" f""" destination module has {len(SCREAMING_SNAKE_CASE_ )}.""" ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = True ) -> Any: print(F"""Converting {name}...""" ) with torch.no_grad(): A: Union[str, Any] = timm.create_model(__lowercase , pretrained=__lowercase ).eval() A: List[str] = ResNetForImageClassification(__lowercase ).eval() A: int = ModuleTransfer(src=__lowercase , dest=__lowercase ) A: List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(__lowercase ) assert torch.allclose(from_model(__lowercase ) , our_model(__lowercase ).logits ), "The model logits don't match the original one." A: str = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(__lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=__lowercase , ) # we can use the convnext one A: Any = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=__lowercase , ) print(F"""Pushed {checkpoint_name}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = None , __lowercase = True ) -> List[Any]: A: Union[str, Any] = '''imagenet-1k-id2label.json''' A: Union[str, Any] = 1_0_0_0 A: Optional[int] = (1, num_labels) A: Dict = '''huggingface/label-files''' A: Any = num_labels A: Union[str, Any] = json.load(open(hf_hub_download(__lowercase , __lowercase , repo_type='''dataset''' ) , '''r''' ) ) A: Optional[int] = {int(__lowercase ): v for k, v in idalabel.items()} A: Optional[int] = idalabel A: List[str] = {v: k for k, v in idalabel.items()} A: str = partial(__lowercase , num_labels=__lowercase , idalabel=__lowercase , labelaid=__lowercase ) A: Optional[Any] = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(__lowercase , names_to_config[model_name] , __lowercase , __lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowercase , __lowercase , __lowercase , __lowercase ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def _snake_case ( self : Optional[Any] ) -> int: '''simple docstring''' A: int = SMALL_MODEL_IDENTIFIER A: List[str] = '''pt''' A: Optional[Any] = '''tf''' def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> int: '''simple docstring''' A: Any = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' A: Tuple = TFAutoModel.from_pretrained(self.test_model , from_pt=SCREAMING_SNAKE_CASE_ ) model_tf.save_pretrained(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' A: List[str] = '''mock_framework''' # Framework provided - return whatever the user provides A: Tuple = FeaturesManager.determine_framework(self.test_model , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(SCREAMING_SNAKE_CASE_ ) A: List[str] = FeaturesManager.determine_framework(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = FeaturesManager.determine_framework(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Any ) -> str: '''simple docstring''' with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(SCREAMING_SNAKE_CASE_ ) A: int = FeaturesManager.determine_framework(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(SCREAMING_SNAKE_CASE_ ) A: Dict = FeaturesManager.determine_framework(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = FeaturesManager.determine_framework(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : str ) -> int: '''simple docstring''' A: Any = MagicMock(return_value=SCREAMING_SNAKE_CASE_ ) with patch('''transformers.onnx.features.is_tf_available''' , SCREAMING_SNAKE_CASE_ ): A: Optional[int] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(SCREAMING_SNAKE_CASE_ , self.framework_pt ) # PyTorch not in environment -> use TensorFlow A: Dict = MagicMock(return_value=SCREAMING_SNAKE_CASE_ ) with patch('''transformers.onnx.features.is_torch_available''' , SCREAMING_SNAKE_CASE_ ): A: List[str] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(SCREAMING_SNAKE_CASE_ , self.framework_tf ) # Both in environment -> use PyTorch A: Dict = MagicMock(return_value=SCREAMING_SNAKE_CASE_ ) A: Any = MagicMock(return_value=SCREAMING_SNAKE_CASE_ ) with patch('''transformers.onnx.features.is_tf_available''' , SCREAMING_SNAKE_CASE_ ), patch( '''transformers.onnx.features.is_torch_available''' , SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(SCREAMING_SNAKE_CASE_ , self.framework_pt ) # Both not in environment -> raise error A: List[Any] = MagicMock(return_value=SCREAMING_SNAKE_CASE_ ) A: Any = MagicMock(return_value=SCREAMING_SNAKE_CASE_ ) with patch('''transformers.onnx.features.is_tf_available''' , SCREAMING_SNAKE_CASE_ ), patch( '''transformers.onnx.features.is_torch_available''' , SCREAMING_SNAKE_CASE_ ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): A: Dict = FeaturesManager.determine_framework(self.test_model )
367
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str | Literal[False]: A: List[str] = list(__lowercase ) A: Optional[Any] = list(__lowercase ) A: int = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count += 1 A: Optional[Any] = '''_''' if count > 1: return False else: return "".join(__lowercase ) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[str]: A: Any = [] while True: A: Dict = ['''$'''] * len(__lowercase ) A: Union[str, Any] = [] for i in range(len(__lowercase ) ): for j in range(i + 1 , len(__lowercase ) ): A: Any = compare_string(binary[i] , binary[j] ) if k is False: A: Any = '''*''' A: List[Any] = '''*''' temp.append('''X''' ) for i in range(len(__lowercase ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__lowercase ) == 0: return pi A: List[Any] = list(set(__lowercase ) ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: Optional[int] = [] for minterm in minterms: A: Optional[int] = '''''' for _ in range(__lowercase ): A: List[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(__lowercase ) return temp def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> bool: A: Union[str, Any] = list(__lowercase ) A: Union[str, Any] = list(__lowercase ) A: Optional[int] = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: List[Any] = [] A: Dict = [0] * len(__lowercase ) for i in range(len(chart[0] ) ): A: List[str] = 0 A: str = -1 for j in range(len(__lowercase ) ): if chart[j][i] == 1: count += 1 A: Any = j if count == 1: A: Any = 1 for i in range(len(__lowercase ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(__lowercase ) ): A: Optional[int] = 0 temp.append(prime_implicants[i] ) while True: A: Dict = 0 A: Optional[int] = -1 A: Dict = 0 for i in range(len(__lowercase ) ): A: str = chart[i].count(1 ) if count_n > max_n: A: Tuple = count_n A: Optional[Any] = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(__lowercase ) ): A: Any = 0 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[int]]: A: str = [[0 for x in range(len(__lowercase ) )] for x in range(len(__lowercase ) )] for i in range(len(__lowercase ) ): A: Tuple = prime_implicants[i].count('''_''' ) for j in range(len(__lowercase ) ): if is_for_table(prime_implicants[i] , binary[j] , __lowercase ): A: Optional[Any] = 1 return chart def SCREAMING_SNAKE_CASE( ) -> None: A: int = int(input('''Enter the no. of variables\n''' ) ) A: Optional[int] = [ float(__lowercase ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] A: List[str] = decimal_to_binary(__lowercase , __lowercase ) A: str = check(__lowercase ) print('''Prime Implicants are:''' ) print(__lowercase ) A: List[Any] = prime_implicant_chart(__lowercase , __lowercase ) A: Any = selection(__lowercase , __lowercase ) print('''Essential Prime Implicants are:''' ) print(__lowercase ) if __name__ == "__main__": import doctest doctest.testmod() main()
334
0
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : List[str] UpperCamelCase_ : Optional[str] = None # Automatically constructed UpperCamelCase_ : ClassVar[str] = "dict" UpperCamelCase_ : ClassVar[Any] = None UpperCamelCase_ : str = field(default="""Translation""" , init=UpperCAmelCase_ , repr=UpperCAmelCase_ ) def __call__( self : Dict ) -> List[Any]: '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def _snake_case ( self : Dict ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : Optional[List] = None UpperCamelCase_ : Optional[int] = None UpperCamelCase_ : Optional[str] = None # Automatically constructed UpperCamelCase_ : ClassVar[str] = "dict" UpperCamelCase_ : ClassVar[Any] = None UpperCamelCase_ : str = field(default="""TranslationVariableLanguages""" , init=UpperCAmelCase_ , repr=UpperCAmelCase_ ) def _snake_case ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' A: int = sorted(set(self.languages ) ) if self.languages else None A: str = len(self.languages ) if self.languages else None def __call__( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def _snake_case ( self : Dict , SCREAMING_SNAKE_CASE_ : Tuple ) -> List[str]: '''simple docstring''' A: Tuple = set(self.languages ) if self.languages and set(SCREAMING_SNAKE_CASE_ ) - lang_set: raise ValueError( f"""Some languages in example ({', '.join(sorted(set(SCREAMING_SNAKE_CASE_ ) - lang_set ) )}) are not in valid set ({', '.join(SCREAMING_SNAKE_CASE_ )}).""" ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. A: str = [] for lang, text in translation_dict.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. A: Tuple = zip(*sorted(SCREAMING_SNAKE_CASE_ ) ) return {"language": languages, "translation": translations} def _snake_case ( self : Any ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
368
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> Tuple: A: Tuple = len(__lowercase ) for i in range(length - 1 ): A: Dict = i for k in range(i + 1 , __lowercase ): if collection[k] < collection[least]: A: List[str] = k if least != i: A , A: Tuple = (collection[i], collection[least]) return collection if __name__ == "__main__": UpperCamelCase = input('''Enter numbers separated by a comma:\n''').strip() UpperCamelCase = [int(item) for item in user_input.split(''',''')] print(selection_sort(unsorted))
334
0
'''simple docstring''' import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : int = (PNDMScheduler,) UpperCamelCase_ : List[Any] = (("""num_inference_steps""", 50),) def _snake_case ( self : Tuple , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Any: '''simple docstring''' A: Optional[Any] = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _snake_case ( self : Dict , SCREAMING_SNAKE_CASE_ : int=0 , **SCREAMING_SNAKE_CASE_ : Dict ) -> List[str]: '''simple docstring''' A: List[str] = dict(self.forward_default_kwargs ) A: Union[str, Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE_ ) A: int = self.dummy_sample A: Optional[int] = 0.1 * sample A: List[str] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: A: List[str] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals A: int = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals A: Union[str, Any] = dummy_past_residuals[:] A: Any = scheduler.step_prk(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Union[str, Any] = new_scheduler.step_prk(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" A: Union[str, Any] = scheduler.step_plms(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Tuple = new_scheduler.step_plms(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _snake_case ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' pass def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any]=0 , **SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = dict(self.forward_default_kwargs ) A: Optional[Any] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = self.dummy_sample A: Tuple = 0.1 * sample A: List[str] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: A: Union[str, Any] = self.get_scheduler_config() A: Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals (must be after setting timesteps) A: str = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(SCREAMING_SNAKE_CASE_ ) A: List[str] = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residuals new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # copy over dummy past residual (must be after setting timesteps) A: str = dummy_past_residuals[:] A: str = scheduler.step_prk(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Any = new_scheduler.step_prk(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" A: int = scheduler.step_plms(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Union[str, Any] = new_scheduler.step_plms(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _snake_case ( self : List[Any] , **SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' A: List[Any] = self.scheduler_classes[0] A: Any = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) A: List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) A: List[str] = 10 A: str = self.dummy_model() A: str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.prk_timesteps ): A: Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: str = scheduler.step_prk(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): A: Dict = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Dict = scheduler.step_plms(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def _snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' A: List[str] = dict(self.forward_default_kwargs ) A: Optional[int] = kwargs.pop('''num_inference_steps''' , SCREAMING_SNAKE_CASE_ ) for scheduler_class in self.scheduler_classes: A: Optional[int] = self.get_scheduler_config() A: List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) A: List[str] = self.dummy_sample A: Tuple = 0.1 * sample if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE_ , '''set_timesteps''' ): scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE_ , '''set_timesteps''' ): A: Dict = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) A: Tuple = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] A: Dict = dummy_past_residuals[:] A: List[Any] = scheduler.step_prk(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Union[str, Any] = scheduler.step_prk(SCREAMING_SNAKE_CASE_ , 1 , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) A: Optional[int] = scheduler.step_plms(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample A: Dict = scheduler.step_plms(SCREAMING_SNAKE_CASE_ , 1 , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self : Any ) -> Dict: '''simple docstring''' for timesteps in [1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] ) -> Any: '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) A: Optional[int] = self.scheduler_classes[0] A: List[str] = self.get_scheduler_config(steps_offset=1 ) A: int = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [9_01, 8_51, 8_51, 8_01, 8_01, 7_51, 7_51, 7_01, 7_01, 6_51, 6_51, 6_01, 6_01, 5_01, 4_01, 3_01, 2_01, 1_01, 1] ) , ) def _snake_case ( self : Any ) -> List[Any]: '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[str] ) -> List[str]: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> List[str]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int ) -> str: '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ): self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' A: Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: A: int = self.dummy_sample A: List[Any] = 0.1 * sample A: str = self.get_scheduler_config() A: List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): A: str = scheduler.step_prk(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample def _snake_case ( self : int ) -> str: '''simple docstring''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): A: List[str] = self.scheduler_classes[0] A: Tuple = self.get_scheduler_config() A: List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def _snake_case ( self : int ) -> Tuple: '''simple docstring''' A: Optional[int] = self.full_loop() A: int = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) A: Dict = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 198.1318 ) < 1E-2 assert abs(result_mean.item() - 0.2580 ) < 1E-3 def _snake_case ( self : Dict ) -> Tuple: '''simple docstring''' A: List[str] = self.full_loop(prediction_type='''v_prediction''' ) A: List[str] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) A: str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 67.3986 ) < 1E-2 assert abs(result_mean.item() - 0.0878 ) < 1E-3 def _snake_case ( self : List[str] ) -> List[str]: '''simple docstring''' A: str = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) A: str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) A: Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 230.0399 ) < 1E-2 assert abs(result_mean.item() - 0.2995 ) < 1E-3 def _snake_case ( self : Union[str, Any] ) -> int: '''simple docstring''' A: int = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) A: List[Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) A: int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 186.9482 ) < 1E-2 assert abs(result_mean.item() - 0.2434 ) < 1E-3
369
'''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> int: '''simple docstring''' A: Tuple = None A: Dict = None A: Optional[int] = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: str = len(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = None def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ) -> str: '''simple docstring''' if sources is int: A: Union[str, Any] = [sources] if sinks is int: A: Tuple = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return A: List[str] = sources[0] A: Optional[int] = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: A: Any = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A: Dict = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A: Optional[Any] = max_input_flow A: Optional[Any] = 0 A: str = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A: Optional[Any] = max_input_flow A: str = size - 1 def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple: '''simple docstring''' A: Optional[Any] = algorithm(self ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: '''simple docstring''' A: str = flow_network A: List[str] = flow_network.verticesCount A: Dict = flow_network.sourceIndex A: Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A: str = flow_network.graph A: str = False def _snake_case ( self : int ) -> Union[str, Any]: '''simple docstring''' if not self.executed: self._algorithm() A: str = True def _snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' pass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result A: Any = -1 def _snake_case ( self : List[str] ) -> Optional[Any]: '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [[0] * self.verticies_count for i in range(self.verticies_count )] A: Any = [0] * self.verticies_count A: Optional[Any] = [0] * self.verticies_count def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' A: Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A: str = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A: Dict = 0 while i < len(SCREAMING_SNAKE_CASE_ ): A: Any = vertices_list[i] A: str = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) A: Tuple = 0 else: i += 1 A: Tuple = sum(self.preflow[self.source_index] ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: '''simple docstring''' A: Optional[int] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str ) -> int: '''simple docstring''' A: Optional[Any] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A: List[Any] = self.heights[to_index] if min_height is not None: A: int = min_height + 1 if __name__ == "__main__": UpperCamelCase = [0] UpperCamelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCamelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCamelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCamelCase = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('''The given input must be positive''' ) # get the generated string sequence A: Optional[int] = gray_code_sequence_string(__lowercase ) # # convert them to integers for i in range(len(__lowercase ) ): A: Dict = int(sequence[i] , 2 ) return sequence def SCREAMING_SNAKE_CASE( __lowercase ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] A: int = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits A: Union[str, Any] = gray_code_sequence_string(bit_count - 1 ) A: Dict = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): A: List[str] = '''0''' + smaller_sequence[i] sequence.append(__lowercase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): A: List[Any] = '''1''' + smaller_sequence[i] sequence.append(__lowercase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
370
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
334
0
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Any: # Checks if the entire collection has been sorted if len(__lowercase ) <= 1 or n <= 1: return insert_next(__lowercase , n - 1 ) rec_insertion_sort(__lowercase , n - 1 ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Dict: # Checks order between adjacent elements if index >= len(__lowercase ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order A: List[str] = ( collection[index], collection[index - 1], ) insert_next(__lowercase , index + 1 ) if __name__ == "__main__": UpperCamelCase = input('''Enter integers separated by spaces: ''') UpperCamelCase = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
371
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = DebertaTokenizer UpperCamelCase_ : List[str] = True UpperCamelCase_ : int = DebertaTokenizerFast def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A: Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] A: int = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A: Union[str, Any] = {'''unk_token''': '''[UNK]'''} A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: str = 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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : int , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = '''lower newer''' A: str = '''lower newer''' return input_text, output_text def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: str = self.get_tokenizer() A: Any = '''lower newer''' A: Dict = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] A: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokens + [tokenizer.unk_token] A: int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' A: str = self.get_tokenizer() A: List[str] = tokenizer('''Hello''' , '''World''' ) A: Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Tuple ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) A: int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _snake_case ( self : Tuple ) -> Dict: '''simple docstring''' A: int = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: A: List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Dict = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] A: Dict = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: Any = [tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) for seq in encoding['''input_ids''']] # fmt: off A: Any = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on A: Optional[int] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , SCREAMING_SNAKE_CASE_ ) for expected, decoded in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''MLukeTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] , 1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
334
0
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCamelCase = '''src/transformers''' UpperCamelCase = '''docs/source/en''' UpperCamelCase = '''.''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> int: with open(__lowercase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A: str = f.readlines() # Find the start prompt. A: Union[str, Any] = 0 while not lines[start_index].startswith(__lowercase ): start_index += 1 start_index += 1 A: Union[str, Any] = start_index while not lines[end_index].startswith(__lowercase ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCamelCase = '''Model|Encoder|Decoder|ForConditionalGeneration''' # Regexes that match TF/Flax/PT model names. UpperCamelCase = re.compile(R'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') UpperCamelCase = re.compile(R'''Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCamelCase = re.compile(R'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # This is to make sure the transformers module imported is the one in the repo. UpperCamelCase = direct_transformers_import(TRANSFORMERS_PATH) def SCREAMING_SNAKE_CASE( __lowercase ) -> Any: A: Union[str, Any] = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __lowercase ) return [m.group(0 ) for m in matches] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[Any]: A: List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__lowercase ) A: Union[str, Any] = (width - text_length) // 2 A: Union[str, Any] = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def SCREAMING_SNAKE_CASE( ) -> Optional[int]: A: Dict = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES A: Optional[int] = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } A: str = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. A: Dict = collections.defaultdict(__lowercase ) A: Dict = collections.defaultdict(__lowercase ) A: str = collections.defaultdict(__lowercase ) A: List[Any] = collections.defaultdict(__lowercase ) A: str = collections.defaultdict(__lowercase ) # Let's lookup through all transformers object (once). for attr_name in dir(__lowercase ): A: Any = None if attr_name.endswith('''Tokenizer''' ): A: List[str] = slow_tokenizers A: Tuple = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): A: Union[str, Any] = fast_tokenizers A: int = attr_name[:-1_3] elif _re_tf_models.match(__lowercase ) is not None: A: List[Any] = tf_models A: List[Any] = _re_tf_models.match(__lowercase ).groups()[0] elif _re_flax_models.match(__lowercase ) is not None: A: int = flax_models A: Optional[int] = _re_flax_models.match(__lowercase ).groups()[0] elif _re_pt_models.match(__lowercase ) is not None: A: Optional[Any] = pt_models A: Tuple = _re_pt_models.match(__lowercase ).groups()[0] if lookup_dict is not None: while len(__lowercase ) > 0: if attr_name in model_name_to_prefix.values(): A: Dict = True break # Try again after removing the last word in the name A: Dict = ''''''.join(camel_case_split(__lowercase )[:-1] ) # Let's build that table! A: List[Any] = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) A: int = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). A: Tuple = [len(__lowercase ) + 2 for c in columns] A: List[str] = max([len(__lowercase ) for name in model_names] ) + 2 # Build the table per se A: Union[str, Any] = '''|''' + '''|'''.join([_center_text(__lowercase , __lowercase ) for c, w in zip(__lowercase , __lowercase )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" A: Optional[int] = {True: '''✅''', False: '''❌'''} for name in model_names: A: Union[str, Any] = model_name_to_prefix[name] A: Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__lowercase , __lowercase ) for l, w in zip(__lowercase , __lowercase )] ) + "|\n" return table def SCREAMING_SNAKE_CASE( __lowercase=False ) -> List[Any]: A: List[Any] = _find_text_in_file( filename=os.path.join(__lowercase , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) A: Optional[int] = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__lowercase , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') UpperCamelCase = parser.parse_args() check_model_table(args.fix_and_overwrite)
351
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } UpperCamelCase = { '''camembert-base''': 512, } UpperCamelCase = '''▁''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : str = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : int = CamembertTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : str="<s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE_ : List[Any]="</s>" , SCREAMING_SNAKE_CASE_ : int="<s>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<unk>" , SCREAMING_SNAKE_CASE_ : str="<pad>" , SCREAMING_SNAKE_CASE_ : List[str]="<mask>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , **SCREAMING_SNAKE_CASE_ : Any , ) -> Any: '''simple docstring''' A: Tuple = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Any = vocab_file A: Any = False if not self.vocab_file else True def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''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: List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: List[str] = [self.sep_token_id] A: Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return A: Dict = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
334
0
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate UpperCamelCase = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('''''', '''|''', '''|'''), datarow=DataRow('''''', '''|''', '''|'''), padding=1, with_header_hide=None, ) UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = {'''type''': '''section''', '''text''': {'''type''': '''plain_text''', '''text''': '''No failed tests! 🤗''', '''emoji''': True}} UpperCamelCase = [ { '''type''': '''header''', '''text''': { '''type''': '''plain_text''', '''text''': f'🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results', '''emoji''': True, }, } ] UpperCamelCase = 0 for log in Path().glob('''*.log'''): UpperCamelCase = 0 with open(log, '''r''') as f: for line in f: UpperCamelCase = json.loads(line) if line.get('''nodeid''', '''''') != "": UpperCamelCase = line['''nodeid'''] if line.get('''duration''', None) is not None: UpperCamelCase = f'{line["duration"]:.4f}' if line.get('''outcome''', '''''') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('''_''')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) UpperCamelCase = [] log.unlink() UpperCamelCase = '''''' UpperCamelCase = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" UpperCamelCase = [] UpperCamelCase = {} for test in failed_tests: UpperCamelCase = test[0].split('''::''') UpperCamelCase = data[0].split('''/''')[-1] if data[0] not in filesafailed: UpperCamelCase = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) UpperCamelCase = [test[0] for test in failed_table] UpperCamelCase = list(set(files)) # Count number of instances in failed_tests UpperCamelCase = [] for file in individual_files: table.append([file, len(filesafailed[file])]) UpperCamelCase = tabulate( table, headers=['''Test Location''', '''Num Failed'''], tablefmt=hf_table_format, stralign='''right''', ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3000: UpperCamelCase = '''Too many failed tests, please see the full report in the Action results.''' UpperCamelCase = len(err) + 10 UpperCamelCase = message[: 3000 - offset] + f'\n...\n```\n{err}' print(f'### {message}') else: UpperCamelCase = '''No failed tests! 🤗''' print(f'## {message}') payload.append(no_error_payload) if os.environ.get('''TEST_TYPE''', '''''') != "": from slack_sdk import WebClient UpperCamelCase = WebClient(token=os.environ['''SLACK_API_TOKEN''']) if message != "No failed tests! 🤗": UpperCamelCase = { '''type''': '''section''', '''text''': { '''type''': '''mrkdwn''', '''text''': message, }, } payload.append(md_report) UpperCamelCase = { '''type''': '''section''', '''text''': { '''type''': '''mrkdwn''', '''text''': '''*For more details:*''', }, '''accessory''': { '''type''': '''button''', '''text''': { '''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True, }, '''url''': f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } payload.append(action_button) UpperCamelCase = { '''type''': '''context''', '''elements''': [ { '''type''': '''plain_text''', '''text''': f'Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}', } ], } payload.append(date_report) UpperCamelCase = client.chat_postMessage(channel='''#accelerate-ci-daily''', text=message, blocks=payload) UpperCamelCase = response.data['''ts'''] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name UpperCamelCase = '''''' for i, row in enumerate(test_failures): if row[0] != test_class: UpperCamelCase = row[0] else: UpperCamelCase = '''''' UpperCamelCase = { '''type''': '''section''', '''text''': { '''type''': '''mrkdwn''', '''text''': f'Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```', }, } client.chat_postMessage( channel='''#accelerate-ci-daily''', thread_ts=ts, blocks=[payload], )
352
'''simple docstring''' import os from distutils.util import strtobool def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> List[Any]: for e in env_keys: A: Dict = int(os.environ.get(__lowercase , -1 ) ) if val >= 0: return val return default def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=False ) -> List[str]: A: str = os.environ.get(__lowercase , str(__lowercase ) ) return strtobool(__lowercase ) == 1 # As its name indicates `strtobool` actually returns an int... def SCREAMING_SNAKE_CASE( __lowercase , __lowercase="no" ) -> str: A: Optional[int] = os.environ.get(__lowercase , str(__lowercase ) ) return value
334
0
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput UpperCamelCase = 8 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=BITS ) -> List[Any]: A: Dict = x.device A: Any = (x * 2_5_5).int().clamp(0 , 2_5_5 ) A: Any = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__lowercase ) A: Optional[int] = rearrange(__lowercase , '''d -> d 1 1''' ) A: str = rearrange(__lowercase , '''b c h w -> b c 1 h w''' ) A: int = ((x & mask) != 0).float() A: Any = rearrange(__lowercase , '''b c d h w -> b (c d) h w''' ) A: Optional[Any] = bits * 2 - 1 return bits def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=BITS ) -> Union[str, Any]: A: Dict = x.device A: Tuple = (x > 0).int() A: int = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__lowercase , dtype=torch.intaa ) A: Any = rearrange(__lowercase , '''d -> d 1 1''' ) A: List[str] = rearrange(__lowercase , '''b (c d) h w -> b c d h w''' , d=8 ) A: Union[str, Any] = reduce(x * mask , '''b c d h w -> b c h w''' , '''sum''' ) return (dec / 2_5_5).clamp(0.0 , 1.0 ) def SCREAMING_SNAKE_CASE( self , __lowercase , __lowercase , __lowercase , __lowercase = 0.0 , __lowercase = True , __lowercase=None , __lowercase = True , ) -> Union[DDIMSchedulerOutput, Tuple]: 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''' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) A: List[str] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas A: List[Any] = self.alphas_cumprod[timestep] A: List[str] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod A: str = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A: str = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" A: str = self.bit_scale if self.config.clip_sample: A: Optional[int] = torch.clamp(__lowercase , -scale , __lowercase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) A: int = self._get_variance(__lowercase , __lowercase ) A: Optional[Any] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide A: Optional[int] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A: List[str] = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A: List[Any] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 A: int = model_output.device if torch.is_tensor(__lowercase ) else '''cpu''' A: int = torch.randn(model_output.shape , dtype=model_output.dtype , generator=__lowercase ).to(__lowercase ) A: Optional[Any] = self._get_variance(__lowercase , __lowercase ) ** 0.5 * eta * noise A: Any = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=__lowercase , pred_original_sample=__lowercase ) def SCREAMING_SNAKE_CASE( self , __lowercase , __lowercase , __lowercase , __lowercase="epsilon" , __lowercase=None , __lowercase = True , ) -> Union[DDPMSchedulerOutput, Tuple]: A: str = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: A: str = torch.split(__lowercase , sample.shape[1] , dim=1 ) else: A: Union[str, Any] = None # 1. compute alphas, betas A: Union[str, Any] = self.alphas_cumprod[t] A: Tuple = self.alphas_cumprod[t - 1] if t > 0 else self.one A: int = 1 - alpha_prod_t A: Optional[int] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": A: List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": A: List[Any] = model_output else: raise ValueError(F"""Unsupported prediction_type {prediction_type}.""" ) # 3. Clip "predicted x_0" A: List[Any] = self.bit_scale if self.config.clip_sample: A: Optional[int] = torch.clamp(__lowercase , -scale , __lowercase ) # 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: Optional[int] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t A: Tuple = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf A: Union[str, Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise A: Optional[Any] = 0 if t > 0: A: List[str] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=__lowercase ).to(model_output.device ) A: List[str] = (self._get_variance(__lowercase , predicted_variance=__lowercase ) ** 0.5) * noise A: int = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=__lowercase , pred_original_sample=__lowercase ) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : UNetaDConditionModel , SCREAMING_SNAKE_CASE_ : Union[DDIMScheduler, DDPMScheduler] , SCREAMING_SNAKE_CASE_ : Optional[float] = 1.0 , ) -> Dict: '''simple docstring''' super().__init__() A: Union[str, Any] = bit_scale A: List[Any] = ( ddim_bit_scheduler_step if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] = 2_56 , SCREAMING_SNAKE_CASE_ : Optional[int] = 2_56 , SCREAMING_SNAKE_CASE_ : Optional[int] = 50 , SCREAMING_SNAKE_CASE_ : Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = 1 , SCREAMING_SNAKE_CASE_ : Optional[str] = "pil" , SCREAMING_SNAKE_CASE_ : bool = True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' A: Tuple = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=SCREAMING_SNAKE_CASE_ , ) A: List[str] = decimal_to_bits(SCREAMING_SNAKE_CASE_ ) * self.bit_scale A: Any = latents.to(self.device ) self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual A: Dict = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 A: Optional[int] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample A: List[Any] = bits_to_decimal(SCREAMING_SNAKE_CASE_ ) if output_type == "pil": A: List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
353
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() UpperCamelCase = logging.get_logger('''transformers.models.encodec''') UpperCamelCase = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } UpperCamelCase = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } UpperCamelCase = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } UpperCamelCase = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } UpperCamelCase = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } UpperCamelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } UpperCamelCase = [] UpperCamelCase = [] def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: for attribute in key.split('''.''' ): A: Union[str, Any] = getattr(__lowercase , __lowercase ) if weight_type is not None: A: Tuple = getattr(__lowercase , __lowercase ).shape else: A: str = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": A: Dict = value elif weight_type == "weight_g": A: Tuple = value elif weight_type == "weight_v": A: Any = value elif weight_type == "bias": A: str = value elif weight_type == "running_mean": A: List[Any] = value elif weight_type == "running_var": A: Dict = value elif weight_type == "num_batches_tracked": A: List[str] = value elif weight_type == "weight_ih_l0": A: Dict = value elif weight_type == "weight_hh_l0": A: Optional[int] = value elif weight_type == "bias_ih_l0": A: List[Any] = value elif weight_type == "bias_hh_l0": A: str = value elif weight_type == "weight_ih_l1": A: Optional[int] = value elif weight_type == "weight_hh_l1": A: int = value elif weight_type == "bias_ih_l1": A: Optional[Any] = value elif weight_type == "bias_hh_l1": A: str = value else: A: Optional[int] = value logger.info(F"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Optional[Any]: for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: A , A: Any = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> Tuple: A: Any = [] if model_name == "encodec_24khz" or "encodec_32khz": A: List[str] = MAPPING_24K elif model_name == "encodec_48khz": A: List[Any] = MAPPING_48K else: raise ValueError(F"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(__lowercase , __lowercase ): logger.info(F"""{name} was ignored""" ) continue A: Optional[int] = False for key, mapped_key in MAPPING.items(): if "*" in key: A , A: Optional[int] = key.split('''.*.''' ) if prefix in name and suffix in name: A: str = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('''embed''' ) and name.endswith('''embed_avg''' ): continue A: Optional[Any] = True if "*" in mapped_key: A: Any = name.split(__lowercase )[0].split('''.''' )[-2] A: Tuple = mapped_key.replace('''*''' , __lowercase ) if "weight_g" in name: A: str = '''weight_g''' elif "weight_v" in name: A: List[Any] = '''weight_v''' elif "weight_ih_l0" in name: A: Dict = '''weight_ih_l0''' elif "weight_hh_l0" in name: A: int = '''weight_hh_l0''' elif "bias_ih_l0" in name: A: Union[str, Any] = '''bias_ih_l0''' elif "bias_hh_l0" in name: A: Tuple = '''bias_hh_l0''' elif "weight_ih_l1" in name: A: int = '''weight_ih_l1''' elif "weight_hh_l1" in name: A: Optional[Any] = '''weight_hh_l1''' elif "bias_ih_l1" in name: A: Dict = '''bias_ih_l1''' elif "bias_hh_l1" in name: A: str = '''bias_hh_l1''' elif "bias" in name: A: Union[str, Any] = '''bias''' elif "weight" in name: A: Dict = '''weight''' elif "running_mean" in name: A: Tuple = '''running_mean''' elif "running_var" in name: A: Any = '''running_var''' elif "num_batches_tracked" in name: A: str = '''num_batches_tracked''' else: A: Tuple = None set_recursively(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) continue if not is_used: unused_weights.append(__lowercase ) logger.warning(F"""Unused weights: {unused_weights}""" ) @torch.no_grad() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase=None , __lowercase=None , ) -> Dict: if config_path is not None: A: Tuple = EncodecConfig.from_pretrained(__lowercase ) else: A: Union[str, Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": A: Union[str, Any] = [8, 5, 4, 4] A: Dict = [2.2] A: List[Any] = 6_4 A: Optional[Any] = 3_2_0_0_0 A: List[Any] = 2_0_4_8 A: Optional[Any] = False A: int = False A: Union[str, Any] = False elif model_name == "encodec_48khz": A: Optional[int] = [8, 5, 4, 2] A: List[Any] = [3.0, 6.0, 1_2.0, 2_4.0] A: List[Any] = 4_8_0_0_0 A: int = 2 A: List[Any] = False A: Any = '''time_group_norm''' A: Optional[Any] = True A: Any = 1.0 A: Any = 0.0_1 else: raise ValueError(F"""Unknown model name: {model_name}""" ) A: str = EncodecModel(__lowercase ) A: Optional[Any] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(__lowercase ) A: Union[str, Any] = torch.load(__lowercase ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights A: Optional[int] = original_checkpoint['''best_state'''] recursively_load_weights(__lowercase , __lowercase , __lowercase ) model.save_pretrained(__lowercase ) if repo_id: print('''Pushing to the hub...''' ) feature_extractor.push_to_hub(__lowercase ) model.push_to_hub(__lowercase ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) UpperCamelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
334
0
'''simple docstring''' import random def SCREAMING_SNAKE_CASE( __lowercase ) -> bool: A: List[str] = num - 1 A: Any = 0 while s % 2 == 0: A: str = s // 2 t += 1 for _ in range(5 ): A: List[Any] = random.randrange(2 , num - 1 ) A: List[str] = pow(__lowercase , __lowercase , __lowercase ) if v != 1: A: Optional[int] = 0 while v != (num - 1): if i == t - 1: return False else: A: Optional[Any] = i + 1 A: Union[str, Any] = (v**2) % num return True def SCREAMING_SNAKE_CASE( __lowercase ) -> bool: if num < 2: return False A: str = [ 2, 3, 5, 7, 1_1, 1_3, 1_7, 1_9, 2_3, 2_9, 3_1, 3_7, 4_1, 4_3, 4_7, 5_3, 5_9, 6_1, 6_7, 7_1, 7_3, 7_9, 8_3, 8_9, 9_7, 1_0_1, 1_0_3, 1_0_7, 1_0_9, 1_1_3, 1_2_7, 1_3_1, 1_3_7, 1_3_9, 1_4_9, 1_5_1, 1_5_7, 1_6_3, 1_6_7, 1_7_3, 1_7_9, 1_8_1, 1_9_1, 1_9_3, 1_9_7, 1_9_9, 2_1_1, 2_2_3, 2_2_7, 2_2_9, 2_3_3, 2_3_9, 2_4_1, 2_5_1, 2_5_7, 2_6_3, 2_6_9, 2_7_1, 2_7_7, 2_8_1, 2_8_3, 2_9_3, 3_0_7, 3_1_1, 3_1_3, 3_1_7, 3_3_1, 3_3_7, 3_4_7, 3_4_9, 3_5_3, 3_5_9, 3_6_7, 3_7_3, 3_7_9, 3_8_3, 3_8_9, 3_9_7, 4_0_1, 4_0_9, 4_1_9, 4_2_1, 4_3_1, 4_3_3, 4_3_9, 4_4_3, 4_4_9, 4_5_7, 4_6_1, 4_6_3, 4_6_7, 4_7_9, 4_8_7, 4_9_1, 4_9_9, 5_0_3, 5_0_9, 5_2_1, 5_2_3, 5_4_1, 5_4_7, 5_5_7, 5_6_3, 5_6_9, 5_7_1, 5_7_7, 5_8_7, 5_9_3, 5_9_9, 6_0_1, 6_0_7, 6_1_3, 6_1_7, 6_1_9, 6_3_1, 6_4_1, 6_4_3, 6_4_7, 6_5_3, 6_5_9, 6_6_1, 6_7_3, 6_7_7, 6_8_3, 6_9_1, 7_0_1, 7_0_9, 7_1_9, 7_2_7, 7_3_3, 7_3_9, 7_4_3, 7_5_1, 7_5_7, 7_6_1, 7_6_9, 7_7_3, 7_8_7, 7_9_7, 8_0_9, 8_1_1, 8_2_1, 8_2_3, 8_2_7, 8_2_9, 8_3_9, 8_5_3, 8_5_7, 8_5_9, 8_6_3, 8_7_7, 8_8_1, 8_8_3, 8_8_7, 9_0_7, 9_1_1, 9_1_9, 9_2_9, 9_3_7, 9_4_1, 9_4_7, 9_5_3, 9_6_7, 9_7_1, 9_7_7, 9_8_3, 9_9_1, 9_9_7, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__lowercase ) def SCREAMING_SNAKE_CASE( __lowercase = 1_0_2_4 ) -> int: while True: A: int = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(__lowercase ): return num if __name__ == "__main__": UpperCamelCase = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
354
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import random def SCREAMING_SNAKE_CASE( __lowercase : int , __lowercase : Union[str, Any] , __lowercase : Tuple ) -> Union[str, Any]: A: Union[str, Any] = a[left_index] A: List[Any] = left_index + 1 for j in range(left_index + 1 , __lowercase ): if a[j] < pivot: A: Tuple = a[i], a[j] i += 1 A: Any = a[i - 1], a[left_index] return i - 1 def SCREAMING_SNAKE_CASE( __lowercase : str , __lowercase : str , __lowercase : Dict ) -> Optional[int]: if left < right: A: List[Any] = random.randint(__lowercase , right - 1 ) A: Union[str, Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound A: List[Any] = partition(__lowercase , __lowercase , __lowercase ) quick_sort_random( __lowercase , __lowercase , __lowercase ) # recursive quicksort to the left of the pivot point quick_sort_random( __lowercase , pivot_index + 1 , __lowercase ) # recursive quicksort to the right of the pivot point def SCREAMING_SNAKE_CASE( ) -> Optional[int]: A: str = input('''Enter numbers separated by a comma:\n''' ).strip() A: Dict = [int(__lowercase ) for item in user_input.split(''',''' )] quick_sort_random(__lowercase , 0 , len(__lowercase ) ) print(__lowercase ) if __name__ == "__main__": main()
355
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for data in source_data: for i, el in enumerate(__lowercase ): if len(__lowercase ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__lowercase ) ) return data_lists def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: list[list[float]] = [] for dlist, weight in zip(__lowercase , __lowercase ): A: List[str] = min(__lowercase ) A: Union[str, Any] = max(__lowercase ) A: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: A: List[str] = F"""Invalid weight of {weight:f} provided""" raise ValueError(__lowercase ) score_lists.append(__lowercase ) return score_lists def SCREAMING_SNAKE_CASE( __lowercase ) -> list[float]: A: list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__lowercase ): A: str = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[float]]: A: Any = get_data(__lowercase ) A: str = calculate_each_score(__lowercase , __lowercase ) A: int = generate_final_scores(__lowercase ) # append scores to source data for i, ele in enumerate(__lowercase ): source_data[i].append(__lowercase ) return source_data
334
0
def SCREAMING_SNAKE_CASE( __lowercase ) -> str: A: Optional[int] = 0 A: Dict = len(__lowercase ) for i in range(n - 1 ): for j in range(i + 1 , __lowercase ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def SCREAMING_SNAKE_CASE( __lowercase ) -> Optional[Any]: if len(__lowercase ) <= 1: return arr, 0 A: List[Any] = len(__lowercase ) // 2 A: Optional[Any] = arr[0:mid] A: Optional[Any] = arr[mid:] A: Union[str, Any] = count_inversions_recursive(__lowercase ) A: Any = count_inversions_recursive(__lowercase ) A: int = _count_cross_inversions(__lowercase , __lowercase ) A: Union[str, Any] = inversion_p + inversions_q + cross_inversions return c, num_inversions def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> Optional[int]: A: List[str] = [] A: Dict = 0 while i < len(__lowercase ) and j < len(__lowercase ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(__lowercase ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(__lowercase ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def SCREAMING_SNAKE_CASE( ) -> Tuple: A: Optional[int] = [1_0, 2, 1, 5, 5, 2, 1_1] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) A: List[Any] = count_inversions_bf(__lowercase ) A: Union[str, Any] = count_inversions_recursive(__lowercase ) assert num_inversions_bf == num_inversions_recursive == 8 print('''number of inversions = ''' , __lowercase ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() A: Optional[int] = count_inversions_bf(__lowercase ) A: Dict = count_inversions_recursive(__lowercase ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , __lowercase ) # an empty list should also have zero inversions A: List[Any] = [] A: List[str] = count_inversions_bf(__lowercase ) A: List[Any] = count_inversions_recursive(__lowercase ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , __lowercase ) if __name__ == "__main__": main()
356
'''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 UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''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''' ), }, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = DPRContextEncoderTokenizer class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Dict = VOCAB_FILES_NAMES UpperCamelCase_ : List[str] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Tuple = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Optional[int] = DPRQuestionEncoderTokenizer UpperCamelCase = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) UpperCamelCase = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) UpperCamelCase = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ : '''simple docstring''' def __call__( self : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchEncoding: '''simple docstring''' if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) elif titles is None or texts is None: A: Union[str, Any] = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = titles if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [titles] A: Optional[Any] = texts if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [texts] A: str = len(SCREAMING_SNAKE_CASE_ ) A: List[Any] = questions if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [questions] * n_passages assert len(SCREAMING_SNAKE_CASE_ ) == len( SCREAMING_SNAKE_CASE_ ), f"""There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE_ )} titles and {len(SCREAMING_SNAKE_CASE_ )} texts.""" A: Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: Dict = super().__call__(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: str = { '''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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] } if return_attention_mask is not False: A: Union[str, Any] = [] 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: Optional[Any] = attention_mask return self.pad(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : BatchEncoding , SCREAMING_SNAKE_CASE_ : DPRReaderOutput , SCREAMING_SNAKE_CASE_ : int = 16 , SCREAMING_SNAKE_CASE_ : int = 64 , SCREAMING_SNAKE_CASE_ : int = 4 , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Any = reader_input['''input_ids'''] A , A , A: str = reader_output[:3] A: str = len(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = sorted(range(SCREAMING_SNAKE_CASE_ ) , reverse=SCREAMING_SNAKE_CASE_ , key=relevance_logits.__getitem__ ) A: List[DPRReaderOutput] = [] for doc_id in sorted_docs: A: List[str] = 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: Union[str, Any] = sequence_ids.index(self.pad_token_id ) else: A: int = len(SCREAMING_SNAKE_CASE_ ) A: Dict = 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=SCREAMING_SNAKE_CASE_ , top_spans=SCREAMING_SNAKE_CASE_ , ) 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=SCREAMING_SNAKE_CASE_ , start_index=SCREAMING_SNAKE_CASE_ , end_index=SCREAMING_SNAKE_CASE_ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE_ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Union[str, Any] = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE_ ): 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: Any = sorted(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : x[1] , reverse=SCREAMING_SNAKE_CASE_ ) A: Dict = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]""" A: int = 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(SCREAMING_SNAKE_CASE_ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] = READER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = READER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : Optional[Any] = DPRReaderTokenizer
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''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 UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
357
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import warnings from ..trainer import Trainer from ..utils import logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int]=None , **SCREAMING_SNAKE_CASE_ : Any ) -> Tuple: '''simple docstring''' warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(args=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
358
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' pass class lowerCAmelCase_ : '''simple docstring''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> None: '''simple docstring''' A: Any = data A: Node | None = None def __iter__( self : Optional[int] ) -> List[str]: '''simple docstring''' A: List[str] = self A: Dict = [] while node: if node in visited: raise ContainsLoopError visited.append(SCREAMING_SNAKE_CASE_ ) yield node.data A: str = node.next_node @property def _snake_case ( self : List[str] ) -> bool: '''simple docstring''' try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": UpperCamelCase = Node(1) UpperCamelCase = Node(2) UpperCamelCase = Node(3) UpperCamelCase = Node(4) print(root_node.has_loop) # False UpperCamelCase = root_node.next_node print(root_node.has_loop) # True UpperCamelCase = Node(5) UpperCamelCase = Node(6) UpperCamelCase = Node(5) UpperCamelCase = Node(6) print(root_node.has_loop) # False UpperCamelCase = Node(1) print(root_node.has_loop) # False
334
0
'''simple docstring''' from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) ) -> IIRFilter: A: str = tau * frequency / samplerate A: Optional[Any] = sin(__lowercase ) A: Dict = cos(__lowercase ) A: Optional[Any] = _sin / (2 * q_factor) A: Union[str, Any] = (1 - _cos) / 2 A: Tuple = 1 - _cos A: str = 1 + alpha A: List[str] = -2 * _cos A: Tuple = 1 - alpha A: List[str] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) ) -> IIRFilter: A: Optional[Any] = tau * frequency / samplerate A: Tuple = sin(__lowercase ) A: Dict = cos(__lowercase ) A: Tuple = _sin / (2 * q_factor) A: Any = (1 + _cos) / 2 A: List[Any] = -1 - _cos A: int = 1 + alpha A: Optional[Any] = -2 * _cos A: Optional[int] = 1 - alpha A: Dict = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) ) -> IIRFilter: A: List[Any] = tau * frequency / samplerate A: List[str] = sin(__lowercase ) A: List[Any] = cos(__lowercase ) A: Union[str, Any] = _sin / (2 * q_factor) A: int = _sin / 2 A: List[str] = 0 A: Optional[Any] = -ba A: Optional[Any] = 1 + alpha A: Any = -2 * _cos A: int = 1 - alpha A: Tuple = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) ) -> IIRFilter: A: List[Any] = tau * frequency / samplerate A: Any = sin(__lowercase ) A: Optional[int] = cos(__lowercase ) A: Union[str, Any] = _sin / (2 * q_factor) A: Dict = 1 - alpha A: Dict = -2 * _cos A: str = 1 + alpha A: Any = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) , ) -> IIRFilter: A: Optional[Any] = tau * frequency / samplerate A: Dict = sin(__lowercase ) A: str = cos(__lowercase ) A: Union[str, Any] = _sin / (2 * q_factor) A: Union[str, Any] = 1_0 ** (gain_db / 4_0) A: int = 1 + alpha * big_a A: Tuple = -2 * _cos A: Dict = 1 - alpha * big_a A: Any = 1 + alpha / big_a A: Tuple = -2 * _cos A: List[Any] = 1 - alpha / big_a A: int = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) , ) -> IIRFilter: A: Union[str, Any] = tau * frequency / samplerate A: int = sin(__lowercase ) A: Dict = cos(__lowercase ) A: int = _sin / (2 * q_factor) A: int = 1_0 ** (gain_db / 4_0) A: Optional[int] = (big_a + 1) - (big_a - 1) * _cos A: List[Any] = (big_a + 1) + (big_a - 1) * _cos A: List[Any] = (big_a - 1) - (big_a + 1) * _cos A: List[Any] = (big_a - 1) + (big_a + 1) * _cos A: int = 2 * sqrt(__lowercase ) * alpha A: Tuple = big_a * (pmc + aaa) A: Any = 2 * big_a * mpc A: int = big_a * (pmc - aaa) A: int = ppmc + aaa A: List[Any] = -2 * pmpc A: List[Any] = ppmc - aaa A: str = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = 1 / sqrt(2 ) , ) -> IIRFilter: A: List[Any] = tau * frequency / samplerate A: Union[str, Any] = sin(__lowercase ) A: str = cos(__lowercase ) A: List[Any] = _sin / (2 * q_factor) A: Optional[Any] = 1_0 ** (gain_db / 4_0) A: Optional[Any] = (big_a + 1) - (big_a - 1) * _cos A: List[str] = (big_a + 1) + (big_a - 1) * _cos A: str = (big_a - 1) - (big_a + 1) * _cos A: int = (big_a - 1) + (big_a + 1) * _cos A: List[str] = 2 * sqrt(__lowercase ) * alpha A: Union[str, Any] = big_a * (ppmc + aaa) A: List[Any] = -2 * big_a * pmpc A: Any = big_a * (ppmc - aaa) A: List[Any] = pmc + aaa A: Tuple = 2 * mpc A: Tuple = pmc - aaa A: Optional[int] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
359
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE( __lowercase = 4 ) -> list[list[int]]: A: Tuple = abs(__lowercase ) or 4 return [[1 + x + y * row_size for x in range(__lowercase )] for y in range(__lowercase )] def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(transpose(__lowercase ) ) # OR.. transpose(reverse_column(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_row(reverse_column(__lowercase ) ) # OR.. reverse_column(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: return reverse_column(transpose(__lowercase ) ) # OR.. transpose(reverse_row(matrix)) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Union[str, Any] = [list(__lowercase ) for x in zip(*__lowercase )] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[int] = matrix[::-1] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> list[list[int]]: A: Optional[Any] = [x[::-1] for x in matrix] return matrix def SCREAMING_SNAKE_CASE( __lowercase ) -> None: for i in matrix: print(*__lowercase ) if __name__ == "__main__": UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) UpperCamelCase = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def SCREAMING_SNAKE_CASE( ) -> None: assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
360
'''simple docstring''' from __future__ import annotations import numpy as np def SCREAMING_SNAKE_CASE( __lowercase ) -> Dict: return np.maximum(0 , __lowercase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
334
0
import math def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> float: if initial_intensity < 0: raise ValueError('''The value of intensity cannot be negative''' ) # handling of negative values of initial intensity if angle < 0 or angle > 3_6_0: raise ValueError('''In Malus Law, the angle is in the range 0-360 degrees''' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(__lowercase ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='''malus_law''')
361
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCamelCase = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
334
0
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = FlaxAutoencoderKL @property def _snake_case ( self : Dict ) -> List[str]: '''simple docstring''' A: str = 4 A: Dict = 3 A: Optional[int] = (32, 32) A: Optional[int] = jax.random.PRNGKey(0 ) A: Any = jax.random.uniform(SCREAMING_SNAKE_CASE_ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def _snake_case ( self : Tuple ) -> str: '''simple docstring''' A: str = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } A: Optional[Any] = self.dummy_input return init_dict, inputs_dict
362
'''simple docstring''' from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
363
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : torch.FloatTensor class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' @register_to_config def __init__( self : str , SCREAMING_SNAKE_CASE_ : int = 6_55_36 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 2 , SCREAMING_SNAKE_CASE_ : int = 0 , SCREAMING_SNAKE_CASE_ : str = "fourier" , SCREAMING_SNAKE_CASE_ : bool = True , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , SCREAMING_SNAKE_CASE_ : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , SCREAMING_SNAKE_CASE_ : Tuple[str] = "UNetMidBlock1D" , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : Tuple[int] = (32, 32, 64) , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : int = 8 , SCREAMING_SNAKE_CASE_ : int = 1 , SCREAMING_SNAKE_CASE_ : bool = False , ) -> Tuple: '''simple docstring''' super().__init__() A: Optional[Any] = sample_size # time if time_embedding_type == "fourier": A: Tuple = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=SCREAMING_SNAKE_CASE_ , log=SCREAMING_SNAKE_CASE_ , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ ) A: List[str] = 2 * block_out_channels[0] elif time_embedding_type == "positional": A: str = Timesteps( block_out_channels[0] , flip_sin_to_cos=SCREAMING_SNAKE_CASE_ , downscale_freq_shift=SCREAMING_SNAKE_CASE_ ) A: Any = block_out_channels[0] if use_timestep_embedding: A: Optional[Any] = block_out_channels[0] * 4 A: List[Any] = TimestepEmbedding( in_channels=SCREAMING_SNAKE_CASE_ , time_embed_dim=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , out_dim=block_out_channels[0] , ) A: Optional[Any] = nn.ModuleList([] ) A: str = None A: str = nn.ModuleList([] ) A: Tuple = None # down A: Any = in_channels for i, down_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: Optional[int] = output_channel A: List[Any] = block_out_channels[i] if i == 0: input_channel += extra_in_channels A: List[Any] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[int] = get_down_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(SCREAMING_SNAKE_CASE_ ) # mid A: Union[str, Any] = get_mid_block( SCREAMING_SNAKE_CASE_ , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=SCREAMING_SNAKE_CASE_ , add_downsample=SCREAMING_SNAKE_CASE_ , ) # up A: Optional[Any] = list(reversed(SCREAMING_SNAKE_CASE_ ) ) A: List[str] = reversed_block_out_channels[0] if out_block_type is None: A: int = out_channels else: A: Union[str, Any] = block_out_channels[0] for i, up_block_type in enumerate(SCREAMING_SNAKE_CASE_ ): A: List[Any] = output_channel A: int = ( reversed_block_out_channels[i + 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 else final_upsample_channels ) A: Optional[int] = i == len(SCREAMING_SNAKE_CASE_ ) - 1 A: Optional[Any] = get_up_block( SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(SCREAMING_SNAKE_CASE_ ) A: Any = output_channel # out A: List[str] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) A: Optional[int] = get_out_block( out_block_type=SCREAMING_SNAKE_CASE_ , num_groups_out=SCREAMING_SNAKE_CASE_ , embed_dim=block_out_channels[0] , out_channels=SCREAMING_SNAKE_CASE_ , act_fn=SCREAMING_SNAKE_CASE_ , fc_dim=block_out_channels[-1] // 4 , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : torch.FloatTensor , SCREAMING_SNAKE_CASE_ : Union[torch.Tensor, float, int] , SCREAMING_SNAKE_CASE_ : bool = True , ) -> Union[UNetaDOutput, Tuple]: '''simple docstring''' A: Any = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(SCREAMING_SNAKE_CASE_ ) and len(timesteps.shape ) == 0: A: List[str] = timesteps[None].to(sample.device ) A: int = self.time_proj(SCREAMING_SNAKE_CASE_ ) if self.config.use_timestep_embedding: A: List[Any] = self.time_mlp(SCREAMING_SNAKE_CASE_ ) else: A: str = timestep_embed[..., None] A: Union[str, Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) A: Tuple = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down A: List[str] = () for downsample_block in self.down_blocks: A , A: Optional[int] = downsample_block(hidden_states=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: A: Dict = self.mid_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): A: List[Any] = down_block_res_samples[-1:] A: List[str] = down_block_res_samples[:-1] A: Optional[int] = upsample_block(SCREAMING_SNAKE_CASE_ , res_hidden_states_tuple=SCREAMING_SNAKE_CASE_ , temb=SCREAMING_SNAKE_CASE_ ) # 5. post-process if self.out_block: A: Any = self.out_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not return_dict: return (sample,) return UNetaDOutput(sample=SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } UpperCamelCase = { '''camembert-base''': 512, } UpperCamelCase = '''▁''' class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : str = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : int = CamembertTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : str="<s>" , SCREAMING_SNAKE_CASE_ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE_ : List[Any]="</s>" , SCREAMING_SNAKE_CASE_ : int="<s>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="<unk>" , SCREAMING_SNAKE_CASE_ : str="<pad>" , SCREAMING_SNAKE_CASE_ : List[str]="<mask>" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , **SCREAMING_SNAKE_CASE_ : Any , ) -> Any: '''simple docstring''' A: Tuple = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Any = vocab_file A: Any = False if not self.vocab_file else True def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''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: List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' A: List[str] = [self.sep_token_id] A: Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return A: Dict = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
364
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , *SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Dict ) -> None: '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
334
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase = { '''configuration_mega''': ['''MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegaConfig''', '''MegaOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''MEGA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegaForCausalLM''', '''MegaForMaskedLM''', '''MegaForMultipleChoice''', '''MegaForQuestionAnswering''', '''MegaForSequenceClassification''', '''MegaForTokenClassification''', '''MegaModel''', '''MegaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
365
'''simple docstring''' from collections import deque class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> None: '''simple docstring''' A: Union[str, Any] = process_name # process name A: List[str] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time A: Dict = arrival_time A: Optional[Any] = burst_time # remaining burst time A: Any = 0 # total time of the process wait in ready queue A: Any = 0 # time from arrival time to completion time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int , ) -> None: '''simple docstring''' A: Dict = number_of_queues # time slice of queues that round robin algorithm applied A: int = time_slices # unfinished process is in this ready_queue A: Tuple = queue # current time A: int = current_time # finished process is in this sequence queue A: deque[Process] = deque() def _snake_case ( self : List[Any] ) -> list[str]: '''simple docstring''' A: str = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Optional[int] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Any = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: List[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> list[int]: '''simple docstring''' return [q.burst_time for q in queue] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Process ) -> int: '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> deque[Process]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE_ ) != 0: A: Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 A: Any = 0 # set the process's turnaround time because it is finished A: int = self.current_time - cp.arrival_time # set the completion time A: List[str] = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int ) -> tuple[deque[Process], deque[Process]]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE_ ) ): A: Dict = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time A: Optional[Any] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished A: int = 0 # set the finish time A: Union[str, Any] = self.current_time # update the process' turnaround time because it is finished A: Tuple = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _snake_case ( self : Optional[Any] ) -> deque[Process]: '''simple docstring''' for i in range(self.number_of_queues - 1 ): A , A: Optional[Any] = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])}) UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) UpperCamelCase = MLFQ(number_of_queues, time_slices, queue, 0) UpperCamelCase = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print completion times of processes(P1, P2, P3, P4) print( f'completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print sequence of finished processes print( f'sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}' )
334
0
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> bool: if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True A: List[Any] = 4 A: int = (1 << p) - 1 for _ in range(p - 2 ): A: Optional[int] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
366
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger() @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : List[nn.Module] = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : list = field(default_factory=UpperCAmelCase_ ) def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tensor , SCREAMING_SNAKE_CASE_ : Tensor ) -> int: '''simple docstring''' A: List[str] = len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE_ , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE_ ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tensor ) -> Dict: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE_ ) [x.remove() for x in self.handles] return self @property def _snake_case ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' return list(filter(lambda SCREAMING_SNAKE_CASE_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : nn.Module UpperCamelCase_ : nn.Module UpperCamelCase_ : int = 0 UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) UpperCamelCase_ : List = field(default_factory=UpperCAmelCase_ ) def __call__( self : Any , SCREAMING_SNAKE_CASE_ : Tensor ) -> Optional[Any]: '''simple docstring''' A: Dict = Tracker(self.dest )(SCREAMING_SNAKE_CASE_ ).parametrized A: Tuple = Tracker(self.src )(SCREAMING_SNAKE_CASE_ ).parametrized A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.src_skip , SCREAMING_SNAKE_CASE_ ) ) A: str = list(filter(lambda SCREAMING_SNAKE_CASE_ : type(SCREAMING_SNAKE_CASE_ ) not in self.dest_skip , SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise Exception( f"""Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE_ )} operations while""" f""" destination module has {len(SCREAMING_SNAKE_CASE_ )}.""" ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , __lowercase = True ) -> Any: print(F"""Converting {name}...""" ) with torch.no_grad(): A: Union[str, Any] = timm.create_model(__lowercase , pretrained=__lowercase ).eval() A: List[str] = ResNetForImageClassification(__lowercase ).eval() A: int = ModuleTransfer(src=__lowercase , dest=__lowercase ) A: List[str] = torch.randn((1, 3, 2_2_4, 2_2_4) ) module_transfer(__lowercase ) assert torch.allclose(from_model(__lowercase ) , our_model(__lowercase ).logits ), "The model logits don't match the original one." A: str = F"""resnet{'-'.join(name.split('resnet' ) )}""" print(__lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=__lowercase , ) # we can use the convnext one A: Any = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=__lowercase , ) print(F"""Pushed {checkpoint_name}""" ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase = None , __lowercase = True ) -> List[Any]: A: Union[str, Any] = '''imagenet-1k-id2label.json''' A: Union[str, Any] = 1_0_0_0 A: Optional[int] = (1, num_labels) A: Dict = '''huggingface/label-files''' A: Any = num_labels A: Union[str, Any] = json.load(open(hf_hub_download(__lowercase , __lowercase , repo_type='''dataset''' ) , '''r''' ) ) A: Optional[int] = {int(__lowercase ): v for k, v in idalabel.items()} A: Optional[int] = idalabel A: List[str] = {v: k for k, v in idalabel.items()} A: str = partial(__lowercase , num_labels=__lowercase , idalabel=__lowercase , labelaid=__lowercase ) A: Optional[Any] = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[6_4, 1_2_8, 2_5_6, 5_1_2] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 2_3, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 3_6, 3] , hidden_sizes=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(__lowercase , names_to_config[model_name] , __lowercase , __lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowercase , __lowercase , __lowercase , __lowercase ) return config, expected_shape if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) UpperCamelCase = parser.parse_args() UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
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 UpperCamelCase = random.Random() def SCREAMING_SNAKE_CASE( __lowercase , __lowercase=1.0 , __lowercase=None , __lowercase=None ) -> List[str]: if rng is None: A: List[Any] = 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 lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int]=7 , SCREAMING_SNAKE_CASE_ : Optional[Any]=4_00 , SCREAMING_SNAKE_CASE_ : List[Any]=20_00 , SCREAMING_SNAKE_CASE_ : Tuple=1 , SCREAMING_SNAKE_CASE_ : Dict=0.0 , SCREAMING_SNAKE_CASE_ : int=1_60_00 , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Any=True , ) -> Union[str, Any]: '''simple docstring''' A: Optional[Any] = parent A: Tuple = batch_size A: List[Any] = min_seq_length A: Union[str, Any] = max_seq_length A: Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A: List[Any] = feature_size A: Tuple = padding_value A: Dict = sampling_rate A: Tuple = return_attention_mask A: List[str] = do_normalize def _snake_case ( self : int ) -> List[str]: '''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 _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : str=False , SCREAMING_SNAKE_CASE_ : Tuple=False ) -> Dict: '''simple docstring''' def _flatten(SCREAMING_SNAKE_CASE_ : Optional[Any] ): return list(itertools.chain(*SCREAMING_SNAKE_CASE_ ) ) if equal_length: A: int = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size A: int = [ _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: int = [np.asarray(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] return speech_inputs class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = WavaVecaFeatureExtractor def _snake_case ( self : Optional[int] ) -> Any: '''simple docstring''' A: List[str] = WavaVecaFeatureExtractionTester(self ) def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : int ) -> Any: '''simple docstring''' self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE_ , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE_ , axis=0 ) - 1 ) < 1E-3 ) ) def _snake_case ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' A: str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A: Union[str, Any] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] A: Any = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] # Test not batched input A: List[Any] = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values A: str = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) # Test batched A: Any = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ).input_values A: List[str] = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. A: int = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] A: List[str] = np.asarray(SCREAMING_SNAKE_CASE_ ) A: str = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ).input_values A: List[str] = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def _snake_case ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' A: Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A: Optional[Any] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] A: List[Any] = ['''longest''', '''max_length''', '''do_not_pad'''] A: Tuple = [None, 16_00, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A: Union[str, Any] = feat_extract(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) A: Tuple = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_00] ) self.assertTrue(input_values[0][8_00:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:10_00] ) self.assertTrue(input_values[0][10_00:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:12_00] ) def _snake_case ( self : Any ) -> Optional[Any]: '''simple docstring''' A: Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A: Dict = range(8_00 , 14_00 , 2_00 ) A: Optional[int] = [floats_list((1, x) )[0] for x in lengths] A: Tuple = ['''longest''', '''max_length''', '''do_not_pad'''] A: Union[str, Any] = [None, 16_00, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A: Tuple = feat_extract(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: List[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_00] ) self._check_zero_mean_unit_variance(input_values[1][:10_00] ) self._check_zero_mean_unit_variance(input_values[2][:12_00] ) def _snake_case ( self : Any ) -> Any: '''simple docstring''' A: List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A: List[str] = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] A: Optional[Any] = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10_00 , padding='''max_length''' , return_tensors='''np''' ) A: Tuple = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_00] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' A: int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A: Any = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] A: int = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10_00 , padding='''longest''' , return_tensors='''np''' ) A: List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_00] ) self._check_zero_mean_unit_variance(input_values[1, :10_00] ) 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, 10_00) ) A: int = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] A: int = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=20_00 , padding='''longest''' , return_tensors='''np''' ) A: str = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_00] ) self._check_zero_mean_unit_variance(input_values[1, :10_00] ) 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, 12_00) ) @require_torch def _snake_case ( self : Optional[int] ) -> List[str]: '''simple docstring''' import torch A: Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A: str = np.random.rand(1_00 ).astype(np.floataa ) A: List[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A: Optional[int] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) A: List[str] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def _snake_case ( self : Dict ) -> Tuple: '''simple docstring''' for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: A: Tuple = WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) A: str = WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == '''layer''' )
367
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str | Literal[False]: A: List[str] = list(__lowercase ) A: Optional[Any] = list(__lowercase ) A: int = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count += 1 A: Optional[Any] = '''_''' if count > 1: return False else: return "".join(__lowercase ) def SCREAMING_SNAKE_CASE( __lowercase ) -> list[str]: A: Any = [] while True: A: Dict = ['''$'''] * len(__lowercase ) A: Union[str, Any] = [] for i in range(len(__lowercase ) ): for j in range(i + 1 , len(__lowercase ) ): A: Any = compare_string(binary[i] , binary[j] ) if k is False: A: Any = '''*''' A: List[Any] = '''*''' temp.append('''X''' ) for i in range(len(__lowercase ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__lowercase ) == 0: return pi A: List[Any] = list(set(__lowercase ) ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: Optional[int] = [] for minterm in minterms: A: Optional[int] = '''''' for _ in range(__lowercase ): A: List[Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(__lowercase ) return temp def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase ) -> bool: A: Union[str, Any] = list(__lowercase ) A: Union[str, Any] = list(__lowercase ) A: Optional[int] = 0 for i in range(len(__lowercase ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[str]: A: List[Any] = [] A: Dict = [0] * len(__lowercase ) for i in range(len(chart[0] ) ): A: List[str] = 0 A: str = -1 for j in range(len(__lowercase ) ): if chart[j][i] == 1: count += 1 A: Any = j if count == 1: A: Any = 1 for i in range(len(__lowercase ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(__lowercase ) ): A: Optional[int] = 0 temp.append(prime_implicants[i] ) while True: A: Dict = 0 A: Optional[int] = -1 A: Dict = 0 for i in range(len(__lowercase ) ): A: str = chart[i].count(1 ) if count_n > max_n: A: Tuple = count_n A: Optional[Any] = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(__lowercase ) ): A: Any = 0 def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> list[list[int]]: A: str = [[0 for x in range(len(__lowercase ) )] for x in range(len(__lowercase ) )] for i in range(len(__lowercase ) ): A: Tuple = prime_implicants[i].count('''_''' ) for j in range(len(__lowercase ) ): if is_for_table(prime_implicants[i] , binary[j] , __lowercase ): A: Optional[Any] = 1 return chart def SCREAMING_SNAKE_CASE( ) -> None: A: int = int(input('''Enter the no. of variables\n''' ) ) A: Optional[int] = [ float(__lowercase ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] A: List[str] = decimal_to_binary(__lowercase , __lowercase ) A: str = check(__lowercase ) print('''Prime Implicants are:''' ) print(__lowercase ) A: List[Any] = prime_implicant_chart(__lowercase , __lowercase ) A: Any = selection(__lowercase , __lowercase ) print('''Essential Prime Implicants are:''' ) print(__lowercase ) if __name__ == "__main__": import doctest doctest.testmod() main()
334
0
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. UpperCamelCase = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. UpperCamelCase = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. UpperCamelCase = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> tuple[str, float]: A: Tuple = len([g for position, g in enumerate(__lowercase ) if g == main_target[position]] ) return (item, float(__lowercase )) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> tuple[str, str]: A: Optional[Any] = random.randint(0 , len(__lowercase ) - 1 ) A: int = parent_a[:random_slice] + parent_a[random_slice:] A: Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase ) -> str: A: Optional[int] = list(__lowercase ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: A: Any = random.choice(__lowercase ) return "".join(__lowercase ) def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase , ) -> list[str]: A: List[str] = [] # Generate more children proportionally to the fitness score. A: List[str] = int(parent_a[1] * 1_0_0 ) + 1 A: Tuple = 1_0 if child_n >= 1_0 else child_n for _ in range(__lowercase ): A: List[str] = population_score[random.randint(0 , __lowercase )][0] A: List[str] = crossover(parent_a[0] , __lowercase ) # Append new string to the population list. pop.append(mutate(__lowercase , __lowercase ) ) pop.append(mutate(__lowercase , __lowercase ) ) return pop def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: A: str = F"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(__lowercase ) # Verify that the target contains no genes besides the ones inside genes variable. A: List[str] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: A: Any = F"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(__lowercase ) # Generate random starting population. A: Optional[Any] = [] for _ in range(__lowercase ): population.append(''''''.join([random.choice(__lowercase ) for i in range(len(__lowercase ) )] ) ) # Just some logs to know what the algorithms is doing. A: Optional[Any] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(__lowercase ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. A: Optional[int] = [evaluate(__lowercase , __lowercase ) for item in population] # Check if there is a matching evolution. A: Tuple = sorted(__lowercase , key=lambda __lowercase : x[1] , reverse=__lowercase ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 1_0 == 0: print( F"""\nGeneration: {generation}""" F"""\nTotal Population:{total_population}""" F"""\nBest score: {population_score[0][1]}""" F"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. A: Union[str, Any] = population[: int(N_POPULATION / 3 )] population.clear() population.extend(__lowercase ) # Normalize population score to be between 0 and 1. A: Union[str, Any] = [ (item, score / len(__lowercase )) for item, score in population_score ] # This is selection for i in range(__lowercase ): population.extend(select(population_score[int(__lowercase )] , __lowercase , __lowercase ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(__lowercase ) > N_POPULATION: break if __name__ == "__main__": UpperCamelCase = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) UpperCamelCase = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase = basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
368
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> Tuple: A: Tuple = len(__lowercase ) for i in range(length - 1 ): A: Dict = i for k in range(i + 1 , __lowercase ): if collection[k] < collection[least]: A: List[str] = k if least != i: A , A: Tuple = (collection[i], collection[least]) return collection if __name__ == "__main__": UpperCamelCase = input('''Enter numbers separated by a comma:\n''').strip() UpperCamelCase = [int(item) for item in user_input.split(''',''')] print(selection_sort(unsorted))
334
0
'''simple docstring''' import numpy as np import datasets UpperCamelCase = ''' Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] ''' UpperCamelCase = '''\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } ''' UpperCamelCase = ''' Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric("mahalanobis") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {\'mahalanobis\': array([0.5])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''' , id='''sequence''' ) , id='''X''' ), } ) , ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict ) -> List[Any]: '''simple docstring''' A: int = np.array(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = np.array(SCREAMING_SNAKE_CASE_ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('''Expected `X` to be a 2D vector''' ) if len(reference_distribution.shape ) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''' ) if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' ) # Get mahalanobis distance for each prediction A: Dict = X - np.mean(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = np.cov(reference_distribution.T ) try: A: Any = np.linalg.inv(SCREAMING_SNAKE_CASE_ ) except np.linalg.LinAlgError: A: List[Any] = np.linalg.pinv(SCREAMING_SNAKE_CASE_ ) A: Dict = np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: Optional[int] = np.dot(SCREAMING_SNAKE_CASE_ , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
369
'''simple docstring''' class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> int: '''simple docstring''' A: Tuple = None A: Dict = None A: Optional[int] = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: str = len(SCREAMING_SNAKE_CASE_ ) A: Optional[Any] = None def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ) -> str: '''simple docstring''' if sources is int: A: Union[str, Any] = [sources] if sinks is int: A: Tuple = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return A: List[str] = sources[0] A: Optional[int] = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: A: Any = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A: Dict = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A: Optional[Any] = max_input_flow A: Optional[Any] = 0 A: str = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A: Optional[Any] = max_input_flow A: str = size - 1 def _snake_case ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple: '''simple docstring''' A: Optional[Any] = algorithm(self ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: '''simple docstring''' A: str = flow_network A: List[str] = flow_network.verticesCount A: Dict = flow_network.sourceIndex A: Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A: str = flow_network.graph A: str = False def _snake_case ( self : int ) -> Union[str, Any]: '''simple docstring''' if not self.executed: self._algorithm() A: str = True def _snake_case ( self : Tuple ) -> Optional[Any]: '''simple docstring''' pass class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result A: Any = -1 def _snake_case ( self : List[str] ) -> Optional[Any]: '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[int]: '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A: Optional[int] = [[0] * self.verticies_count for i in range(self.verticies_count )] A: Any = [0] * self.verticies_count A: Optional[Any] = [0] * self.verticies_count def _snake_case ( self : str ) -> Optional[Any]: '''simple docstring''' A: Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A: str = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A: Dict = 0 while i < len(SCREAMING_SNAKE_CASE_ ): A: Any = vertices_list[i] A: str = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) A: Tuple = 0 else: i += 1 A: Tuple = sum(self.preflow[self.source_index] ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : List[str] ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: '''simple docstring''' A: Optional[int] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str ) -> int: '''simple docstring''' A: Optional[Any] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A: List[Any] = self.heights[to_index] if min_height is not None: A: int = min_height + 1 if __name__ == "__main__": UpperCamelCase = [0] UpperCamelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCamelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCamelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCamelCase = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
334
0
'''simple docstring''' import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets UpperCamelCase = '''\ @inproceedings{lin-2004-rouge, title = "{ROUGE}: A Package for Automatic Evaluation of Summaries", author = "Lin, Chin-Yew", booktitle = "Text Summarization Branches Out", month = jul, year = "2004", address = "Barcelona, Spain", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W04-1013", pages = "74--81", } ''' UpperCamelCase = '''\ ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters. This metrics is a wrapper around Google Research reimplementation of ROUGE: https://github.com/google-research/google-research/tree/master/rouge ''' UpperCamelCase = ''' Calculates average rouge scores for a list of hypotheses and references Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. rouge_types: A list of rouge types to calculate. Valid names: `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring, `"rougeL"`: Longest common subsequence based scoring. `"rougeLSum"`: rougeLsum splits text using `"\n"`. See details in https://github.com/huggingface/datasets/issues/617 use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes. use_aggregator: Return aggregates if this is set to True Returns: rouge1: rouge_1 (precision, recall, f1), rouge2: rouge_2 (precision, recall, f1), rougeL: rouge_l (precision, recall, f1), rougeLsum: rouge_lsum (precision, recall, f1) Examples: >>> rouge = datasets.load_metric(\'rouge\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> results = rouge.compute(predictions=predictions, references=references) >>> print(list(results.keys())) [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\'] >>> print(results["rouge1"]) AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0)) >>> print(results["rouge1"].mid.fmeasure) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self : Optional[Any] ) -> str: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/google-research/google-research/tree/master/rouge'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/ROUGE_(metric)''', '''https://github.com/google-research/google-research/tree/master/rouge''', ] , ) def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str=None , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : Any=False ) -> List[str]: '''simple docstring''' if rouge_types is None: A: str = ['''rouge1''', '''rouge2''', '''rougeL''', '''rougeLsum'''] A: Union[str, Any] = rouge_scorer.RougeScorer(rouge_types=SCREAMING_SNAKE_CASE_ , use_stemmer=SCREAMING_SNAKE_CASE_ ) if use_aggregator: A: Union[str, Any] = scoring.BootstrapAggregator() else: A: List[str] = [] for ref, pred in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A: Tuple = scorer.score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if use_aggregator: aggregator.add_scores(SCREAMING_SNAKE_CASE_ ) else: scores.append(SCREAMING_SNAKE_CASE_ ) if use_aggregator: A: Dict = aggregator.aggregate() else: A: Tuple = {} for key in scores[0]: A: str = [score[key] for score in scores] return result
370
'''simple docstring''' from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ["""input_features""", """attention_mask"""] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_60_00 , SCREAMING_SNAKE_CASE_ : int=80 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> List[Any]: '''simple docstring''' super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = num_mel_bins A: str = do_ceptral_normalize A: int = normalize_means A: List[Any] = normalize_vars A: Any = True def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : np.ndarray , ) -> np.ndarray: '''simple docstring''' A: Optional[int] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers A: Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) A: List[Any] = ta_kaldi.fbank(SCREAMING_SNAKE_CASE_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _snake_case ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : Optional[bool] = True , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> np.ndarray: '''simple docstring''' if normalize_means: A: str = x[:input_length].mean(axis=0 ) A: Dict = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if normalize_vars: A: Tuple = x[:input_length].std(axis=0 ) A: List[Any] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: A: Optional[int] = padding_value # make sure array is in float32 A: Optional[Any] = x.astype(np.floataa ) return x def _snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ) -> List[np.ndarray]: '''simple docstring''' A: int = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) A: Any = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) A: Optional[Any] = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A: Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): A: int = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A: Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: A: Union[str, Any] = [raw_speech] # extract fbank features A: str = [self._extract_fbank_features(SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech] # convert into correct format for padding A: int = BatchFeature({'''input_features''': features} ) A: int = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format A: List[str] = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): A: Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] A: List[Any] = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: A: Dict = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A: Dict = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD else None ) A: List[Any] = self.normalize( padded_inputs['''input_features'''] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: A: Dict = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
334
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-classification/requirements.txt''') UpperCamelCase = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) UpperCamelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def SCREAMING_SNAKE_CASE( __lowercase ) -> Any: with open(__lowercase , '''rb''' ) as f: A: str = Image.open(__lowercase ) return im.convert('''RGB''' ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={ """help""": """Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).""" } , ) UpperCamelCase_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) UpperCamelCase_ : Optional[str] = field(default=UpperCAmelCase_ , metadata={"""help""": """A folder containing the training data."""} ) UpperCamelCase_ : Optional[str] = field(default=UpperCAmelCase_ , metadata={"""help""": """A folder containing the validation data."""} ) UpperCamelCase_ : Optional[float] = field( default=0.15 , metadata={"""help""": """Percent to split off of train for validation."""} ) UpperCamelCase_ : Optional[int] = field( default=UpperCAmelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) UpperCamelCase_ : Optional[int] = field( default=UpperCAmelCase_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def _snake_case ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( '''You must specify either a dataset name from the hub or a train and/or validation directory.''' ) @dataclass class lowerCAmelCase_ : '''simple docstring''' UpperCamelCase_ : str = field( default="""google/vit-base-patch16-224-in21k""" , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} , ) UpperCamelCase_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(UpperCAmelCase_ )} , ) UpperCamelCase_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) UpperCamelCase_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""} ) UpperCamelCase_ : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) UpperCamelCase_ : str = field(default=UpperCAmelCase_ , metadata={"""help""": """Name or path of preprocessor config."""} ) UpperCamelCase_ : bool = field( default=UpperCAmelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) UpperCamelCase_ : bool = field( default=UpperCAmelCase_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def SCREAMING_SNAKE_CASE( __lowercase ) -> List[Any]: A: Optional[int] = torch.stack([example['''pixel_values'''] for example in examples] ) A: str = torch.tensor([example['''labels'''] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def SCREAMING_SNAKE_CASE( ) -> int: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. A: Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. A: int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A: List[Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_image_classification''' , __lowercase , __lowercase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A: Tuple = training_args.get_process_log_level() logger.setLevel(__lowercase ) transformers.utils.logging.set_verbosity(__lowercase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. A: Tuple = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A: int = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: A: str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir , task='''image-classification''' , use_auth_token=True if model_args.use_auth_token else None , ) else: A: Optional[int] = {} if data_args.train_dir is not None: A: Optional[int] = os.path.join(data_args.train_dir , '''**''' ) if data_args.validation_dir is not None: A: Optional[int] = os.path.join(data_args.validation_dir , '''**''' ) A: Optional[int] = load_dataset( '''imagefolder''' , data_files=__lowercase , cache_dir=model_args.cache_dir , task='''image-classification''' , ) # If we don't have a validation split, split off a percentage of train as validation. A: Any = None if '''validation''' in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __lowercase ) and data_args.train_val_split > 0.0: A: Optional[int] = dataset['''train'''].train_test_split(data_args.train_val_split ) A: int = split['''train'''] A: Optional[int] = split['''test'''] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. A: int = dataset['''train'''].features['''labels'''].names A: List[Any] = {}, {} for i, label in enumerate(__lowercase ): A: Tuple = str(__lowercase ) A: Tuple = label # Load the accuracy metric from the datasets package A: List[Any] = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__lowercase ): return metric.compute(predictions=np.argmax(p.predictions , axis=1 ) , references=p.label_ids ) A: List[str] = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(__lowercase ) , labelaid=__lowercase , idalabel=__lowercase , finetuning_task='''image-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) A: Optional[int] = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) A: Optional[Any] = AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: A: List[Any] = image_processor.size['''shortest_edge'''] else: A: List[str] = (image_processor.size['''height'''], image_processor.size['''width''']) A: Any = Normalize(mean=image_processor.image_mean , std=image_processor.image_std ) A: Tuple = Compose( [ RandomResizedCrop(__lowercase ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) A: str = Compose( [ Resize(__lowercase ), CenterCrop(__lowercase ), ToTensor(), normalize, ] ) def train_transforms(__lowercase ): A: Optional[int] = [ _train_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image'''] ] return example_batch def val_transforms(__lowercase ): A: Union[str, Any] = [_val_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image''']] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: A: Optional[int] = ( dataset['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(__lowercase ) if training_args.do_eval: if "validation" not in dataset: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: A: Tuple = ( dataset['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(__lowercase ) # Initalize our trainer A: List[str] = Trainer( model=__lowercase , args=__lowercase , train_dataset=dataset['''train'''] if training_args.do_train else None , eval_dataset=dataset['''validation'''] if training_args.do_eval else None , compute_metrics=__lowercase , tokenizer=__lowercase , data_collator=__lowercase , ) # Training if training_args.do_train: A: Union[str, Any] = None if training_args.resume_from_checkpoint is not None: A: Optional[int] = training_args.resume_from_checkpoint elif last_checkpoint is not None: A: str = last_checkpoint A: Tuple = trainer.train(resume_from_checkpoint=__lowercase ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A: Optional[int] = trainer.evaluate() trainer.log_metrics('''eval''' , __lowercase ) trainer.save_metrics('''eval''' , __lowercase ) # Write model card and (optionally) push to hub A: Tuple = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''image-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''image-classification''', '''vision'''], } if training_args.push_to_hub: trainer.push_to_hub(**__lowercase ) else: trainer.create_model_card(**__lowercase ) if __name__ == "__main__": main()
371
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = DebertaTokenizer UpperCamelCase_ : List[str] = True UpperCamelCase_ : int = DebertaTokenizerFast def _snake_case ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A: Optional[int] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] A: int = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) A: Union[str, Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A: Union[str, Any] = {'''unk_token''': '''[UNK]'''} A: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) A: str = 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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _snake_case ( self : int , **SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: '''simple docstring''' A: Optional[int] = '''lower newer''' A: str = '''lower newer''' return input_text, output_text def _snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A: str = self.get_tokenizer() A: Any = '''lower newer''' A: Dict = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] A: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokens + [tokenizer.unk_token] A: int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : List[Any] ) -> Any: '''simple docstring''' A: str = self.get_tokenizer() A: List[str] = tokenizer('''Hello''' , '''World''' ) A: Union[str, Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , SCREAMING_SNAKE_CASE_ ) @slow def _snake_case ( self : Tuple ) -> Optional[int]: '''simple docstring''' A: Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Any = tokenizer.encode('''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: Dict = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) A: List[Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) A: int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _snake_case ( self : Tuple ) -> Dict: '''simple docstring''' A: int = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: A: List[Any] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) A: Dict = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] A: Dict = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) A: Any = [tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) for seq in encoding['''input_ids''']] # fmt: off A: Any = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on A: Optional[int] = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , SCREAMING_SNAKE_CASE_ ) for expected, decoded in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
334
0
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class lowercase : '''simple docstring''' def __init__(self , __a , ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = parent UpperCAmelCase__ = 13 UpperCAmelCase__ = 7 UpperCAmelCase__ = True UpperCAmelCase__ = True UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = 99 UpperCAmelCase__ = 32 UpperCAmelCase__ = 2 UpperCAmelCase__ = 4 UpperCAmelCase__ = 37 UpperCAmelCase__ = 'gelu' UpperCAmelCase__ = 0.1 UpperCAmelCase__ = 0.1 UpperCAmelCase__ = 512 UpperCAmelCase__ = 16 UpperCAmelCase__ = 2 UpperCAmelCase__ = 0.02 UpperCAmelCase__ = 3 UpperCAmelCase__ = 4 UpperCAmelCase__ = None def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ = None if self.use_input_mask: UpperCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase__ = 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 , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ (self , __a , __a , __a , __a , __a , __a ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = TFDistilBertModel(config=__a ) UpperCAmelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase__ = model(__a ) UpperCAmelCase__ = [input_ids, input_mask] UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ (self , __a , __a , __a , __a , __a , __a ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = TFDistilBertForMaskedLM(config=__a ) UpperCAmelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ (self , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" UpperCAmelCase__ = TFDistilBertForQuestionAnswering(config=__a ) UpperCAmelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, } UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ (self , __a , __a , __a , __a , __a , __a ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = TFDistilBertForSequenceClassification(__a ) UpperCAmelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ (self , __a , __a , __a , __a , __a , __a ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.num_choices UpperCAmelCase__ = TFDistilBertForMultipleChoice(__a ) UpperCAmelCase__ = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) UpperCAmelCase__ = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) UpperCAmelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, } UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ (self , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = TFDistilBertForTokenClassification(__a ) UpperCAmelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.prepare_config_and_inputs() ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) = config_and_inputs UpperCAmelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowercase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { """feature-extraction""": TFDistilBertModel, """fill-mask""": TFDistilBertForMaskedLM, """question-answering""": TFDistilBertForQuestionAnswering, """text-classification""": TFDistilBertForSequenceClassification, """token-classification""": TFDistilBertForTokenClassification, """zero-shot""": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def UpperCamelCase__ (self ) -> str: """simple docstring""" UpperCAmelCase__ = TFDistilBertModelTester(self ) UpperCAmelCase__ = ConfigTester(self , config_class=__a , dim=37 ) def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*__a ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*__a ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*__a ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*__a ) def UpperCamelCase__ (self ) -> str: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*__a ) def UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*__a ) @slow def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): UpperCAmelCase__ = TFDistilBertModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_tf class lowercase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = TFDistilBertModel.from_pretrained('distilbert-base-uncased' ) UpperCAmelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase__ = model(__a )[0] UpperCAmelCase__ = [1, 6, 768] self.assertEqual(output.shape , __a ) UpperCAmelCase__ = tf.constant( [ [ [0.19_26_18_85, -0.13_73_29_55, 0.4_11_97_99], [0.22_15_01_56, -0.07_42_26_61, 0.39_03_72_04], [0.22_75_60_18, -0.0_89_64_14, 0.3_70_14_67], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1E-4 )
335
class lowercase : # Public class to implement a graph '''simple docstring''' def __init__(self , __a , __a , __a ) -> None: """simple docstring""" UpperCAmelCase__ = row UpperCAmelCase__ = col UpperCAmelCase__ = graph def UpperCamelCase__ (self , __a , __a , __a ) -> bool: """simple docstring""" return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ (self , __a , __a , __a ) -> None: """simple docstring""" UpperCAmelCase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order UpperCAmelCase__ = [-1, 0, 1, -1, 1, -1, 0, 1] UpperCAmelCase__ = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , __a ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , __a ) def UpperCamelCase__ (self ) -> int: # And finally, count all islands. """simple docstring""" UpperCAmelCase__ = [[False for j in range(self.COL )] for i in range(self.ROW )] UpperCAmelCase__ = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(__a , __a , __a ) count += 1 return count
335
1
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class lowercase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = StableUnCLIPImgaImgPipeline __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_PARAMS __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __SCREAMING_SNAKE_CASE = frozenset([] ) def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ = 32 UpperCAmelCase__ = embedder_hidden_size # image encoding components UpperCAmelCase__ = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) UpperCAmelCase__ = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__a , projection_dim=__a , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) UpperCAmelCase__ = StableUnCLIPImageNormalizer(embedding_dim=__a ) UpperCAmelCase__ = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) UpperCAmelCase__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) UpperCAmelCase__ = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__a , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) UpperCAmelCase__ = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__a , layers_per_block=1 , upcast_attention=__a , use_linear_projection=__a , ) torch.manual_seed(0 ) UpperCAmelCase__ = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type='v_prediction' , set_alpha_to_one=__a , steps_offset=1 , ) torch.manual_seed(0 ) UpperCAmelCase__ = AutoencoderKL() UpperCAmelCase__ = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def UpperCamelCase__ (self , __a , __a=0 , __a=True ) -> List[str]: """simple docstring""" if str(__a ).startswith('mps' ): UpperCAmelCase__ = torch.manual_seed(__a ) else: UpperCAmelCase__ = torch.Generator(device=__a ).manual_seed(__a ) UpperCAmelCase__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) if pil_image: UpperCAmelCase__ = input_image * 0.5 + 0.5 UpperCAmelCase__ = input_image.clamp(0 , 1 ) UpperCAmelCase__ = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCAmelCase__ = DiffusionPipeline.numpy_to_pil(__a )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def UpperCamelCase__ (self ) -> Dict: """simple docstring""" UpperCAmelCase__ = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase__ = self.get_dummy_components() UpperCAmelCase__ = StableUnCLIPImgaImgPipeline(**__a ) UpperCAmelCase__ = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase__ = self.get_dummy_inputs(__a ) inputs.update({'image_embeds': None} ) UpperCAmelCase__ = sd_pipe(**__a ).images UpperCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase__ = np.array([0.38_72, 0.72_24, 0.56_01, 0.47_41, 0.68_72, 0.58_14, 0.46_36, 0.38_67, 0.50_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=__a ) def UpperCamelCase__ (self ) -> str: """simple docstring""" UpperCAmelCase__ = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__a ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__a ) @slow @require_torch_gpu class lowercase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) UpperCAmelCase__ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) UpperCAmelCase__ = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase__ = torch.Generator(device='cpu' ).manual_seed(0 ) UpperCAmelCase__ = pipe(__a , 'anime turle' , generator=__a , output_type='np' ) UpperCAmelCase__ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__a , __a ) def UpperCamelCase__ (self ) -> Any: """simple docstring""" UpperCAmelCase__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) UpperCAmelCase__ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) UpperCAmelCase__ = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase__ = torch.Generator(device='cpu' ).manual_seed(0 ) UpperCAmelCase__ = pipe(__a , 'anime turle' , generator=__a , output_type='np' ) UpperCAmelCase__ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__a , __a ) def UpperCamelCase__ (self ) -> Dict: """simple docstring""" UpperCAmelCase__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase__ = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) UpperCAmelCase__ = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() UpperCAmelCase__ = pipe( __a , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) UpperCAmelCase__ = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
335
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time _UpperCamelCase = Lock() def UpperCamelCase_( snake_case__: Optional[Any] , snake_case__: Optional[int] , snake_case__: Tuple , snake_case__: Tuple , snake_case__: Tuple , snake_case__: Dict , snake_case__: Any ) -> str: global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(snake_case__ ) process_lock.release() # receive your right neighbor's value process_lock.acquire() UpperCAmelCase__ = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left UpperCAmelCase__ = min(snake_case__ , snake_case__ ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(snake_case__ ) process_lock.release() # receive your left neighbor's value process_lock.acquire() UpperCAmelCase__ = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right UpperCAmelCase__ = max(snake_case__ , snake_case__ ) # after all swaps are performed, send the values back to main result_pipe[1].send(snake_case__ ) def UpperCamelCase_( snake_case__: Any ) -> Tuple: UpperCAmelCase__ = [] UpperCAmelCase__ = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop UpperCAmelCase__ = Pipe() UpperCAmelCase__ = Pipe() process_array_.append( Process( target=snake_case__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) UpperCAmelCase__ = temp_rs UpperCAmelCase__ = temp_rr for i in range(1 , len(snake_case__ ) - 1 ): UpperCAmelCase__ = Pipe() UpperCAmelCase__ = Pipe() process_array_.append( Process( target=snake_case__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) UpperCAmelCase__ = temp_rs UpperCAmelCase__ = temp_rr process_array_.append( Process( target=snake_case__ , args=( len(snake_case__ ) - 1, arr[len(snake_case__ ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(snake_case__ ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(snake_case__ ) ): UpperCAmelCase__ = result_pipe[p][0].recv() process_array_[p].join() return arr def UpperCamelCase_( ) -> Dict: UpperCAmelCase__ = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*snake_case__ ) UpperCAmelCase__ = odd_even_transposition(snake_case__ ) print('Sorted List\n' ) print(*snake_case__ ) if __name__ == "__main__": main()
335
1
import sys _UpperCamelCase = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def UpperCamelCase_( snake_case__: str ) -> int: UpperCAmelCase__ = 1 for digit in s: product *= int(snake_case__ ) return product def UpperCamelCase_( snake_case__: str = N ) -> int: UpperCAmelCase__ = -sys.maxsize - 1 UpperCAmelCase__ = n[:13] UpperCAmelCase__ = 13 while cur_index < len(snake_case__ ) - 13: if int(n[cur_index] ) >= int(substr[0] ): UpperCAmelCase__ = substr[1:] + n[cur_index] cur_index += 1 else: UpperCAmelCase__ = max(snake_case__ , str_eval(snake_case__ ) ) UpperCAmelCase__ = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
335
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class lowercase : '''simple docstring''' def __init__(self ) -> str: """simple docstring""" UpperCAmelCase__ = '' UpperCAmelCase__ = '' UpperCAmelCase__ = [] UpperCAmelCase__ = 0 UpperCAmelCase__ = 256 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 def UpperCamelCase__ (self , __a ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = cva.imread(__a , 0 ) UpperCAmelCase__ = copy.deepcopy(self.img ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = plt.hist(self.img.ravel() , 256 , [0, 256] , label='x' ) UpperCAmelCase__ = np.sum(__a ) for i in range(len(__a ) ): UpperCAmelCase__ = x[i] / self.k self.sk += prk UpperCAmelCase__ = (self.L - 1) * self.sk if self.rem != 0: UpperCAmelCase__ = int(last % last ) UpperCAmelCase__ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__a ) UpperCAmelCase__ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCAmelCase__ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCAmelCase__ = self.img[j][i] if num != self.last_list[num]: UpperCAmelCase__ = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": _UpperCamelCase = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') _UpperCamelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
335
1
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING _UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(_UpperCamelCase ) class lowercase ( _UpperCamelCase ): '''simple docstring''' def __init__(self , *__a , **__a ) -> Any: """simple docstring""" super().__init__(*__a , **__a ) requires_backends(self , 'vision' ) self.check_model_type(__a ) def __call__(self , __a , **__a ) -> Tuple: """simple docstring""" return super().__call__(__a , **__a ) def UpperCamelCase__ (self , **__a ) -> List[str]: """simple docstring""" return {}, {}, {} def UpperCamelCase__ (self , __a ) -> Tuple: """simple docstring""" UpperCAmelCase__ = load_image(__a ) UpperCAmelCase__ = image.size UpperCAmelCase__ = self.image_processor(images=__a , return_tensors=self.framework ) return model_inputs def UpperCamelCase__ (self , __a ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.model(**__a ) return model_outputs def UpperCamelCase__ (self , __a ) -> Any: """simple docstring""" UpperCAmelCase__ = model_outputs.predicted_depth UpperCAmelCase__ = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='bicubic' , align_corners=__a ) UpperCAmelCase__ = prediction.squeeze().cpu().numpy() UpperCAmelCase__ = (output * 255 / np.max(__a )).astype('uint8' ) UpperCAmelCase__ = Image.fromarray(__a ) UpperCAmelCase__ = {} UpperCAmelCase__ = predicted_depth UpperCAmelCase__ = depth return output_dict
335
import collections import inspect import unittest from transformers import SwinvaConfig 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, _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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase : '''simple docstring''' def __init__(self , __a , __a=13 , __a=32 , __a=2 , __a=3 , __a=16 , __a=[1, 2, 1] , __a=[2, 2, 4] , __a=2 , __a=2.0 , __a=True , __a=0.0 , __a=0.0 , __a=0.1 , __a="gelu" , __a=False , __a=True , __a=0.02 , __a=1E-5 , __a=True , __a=None , __a=True , __a=10 , __a=8 , ) -> str: """simple docstring""" UpperCAmelCase__ = parent UpperCAmelCase__ = batch_size UpperCAmelCase__ = image_size UpperCAmelCase__ = patch_size UpperCAmelCase__ = num_channels UpperCAmelCase__ = embed_dim UpperCAmelCase__ = depths UpperCAmelCase__ = num_heads UpperCAmelCase__ = window_size UpperCAmelCase__ = mlp_ratio UpperCAmelCase__ = qkv_bias UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = drop_path_rate UpperCAmelCase__ = hidden_act UpperCAmelCase__ = use_absolute_embeddings UpperCAmelCase__ = patch_norm UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = initializer_range UpperCAmelCase__ = is_training UpperCAmelCase__ = scope UpperCAmelCase__ = use_labels UpperCAmelCase__ = type_sequence_label_size UpperCAmelCase__ = encoder_stride def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ = self.get_config() return config, pixel_values, labels def UpperCamelCase__ (self ) -> str: """simple docstring""" return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def UpperCamelCase__ (self , __a , __a , __a ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = SwinvaModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase__ = model(__a ) UpperCAmelCase__ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCAmelCase__ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCamelCase__ (self , __a , __a , __a ) -> Any: """simple docstring""" UpperCAmelCase__ = SwinvaForMaskedImageModeling(config=__a ) model.to(__a ) model.eval() UpperCAmelCase__ = model(__a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCAmelCase__ = 1 UpperCAmelCase__ = SwinvaForMaskedImageModeling(__a ) model.to(__a ) model.eval() UpperCAmelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase__ (self , __a , __a , __a ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.type_sequence_label_size UpperCAmelCase__ = SwinvaForImageClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase__ = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = config_and_inputs UpperCAmelCase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowercase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification} if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def UpperCamelCase__ (self ) -> Any: """simple docstring""" UpperCAmelCase__ = SwinvaModelTester(self ) UpperCAmelCase__ = ConfigTester(self , config_class=__a , embed_dim=37 ) def UpperCamelCase__ (self ) -> Any: """simple docstring""" 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 UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def UpperCamelCase__ (self ) -> int: """simple docstring""" pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" pass def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ = model_class(__a ) UpperCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ = [*signature.parameters.keys()] UpperCAmelCase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ = True for model_class in self.all_model_classes: UpperCAmelCase__ = True UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): UpperCAmelCase__ = model(**self._prepare_for_class(__a , __a ) ) UpperCAmelCase__ = outputs.attentions UpperCAmelCase__ = len(self.model_tester.depths ) self.assertEqual(len(__a ) , __a ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCAmelCase__ = True UpperCAmelCase__ = config.window_size**2 UpperCAmelCase__ = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): UpperCAmelCase__ = model(**self._prepare_for_class(__a , __a ) ) UpperCAmelCase__ = outputs.attentions self.assertEqual(len(__a ) , __a ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) UpperCAmelCase__ = len(__a ) # Check attention is always last and order is fine UpperCAmelCase__ = True UpperCAmelCase__ = True UpperCAmelCase__ = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): UpperCAmelCase__ = model(**self._prepare_for_class(__a , __a ) ) if hasattr(self.model_tester , 'num_hidden_states_types' ): UpperCAmelCase__ = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states UpperCAmelCase__ = 2 self.assertEqual(out_len + added_hidden_states , len(__a ) ) UpperCAmelCase__ = outputs.attentions self.assertEqual(len(__a ) , __a ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def UpperCamelCase__ (self , __a , __a , __a , __a ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): UpperCAmelCase__ = model(**self._prepare_for_class(__a , __a ) ) UpperCAmelCase__ = outputs.hidden_states UpperCAmelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__a ) , __a ) # Swinv2 has a different seq_length UpperCAmelCase__ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCAmelCase__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) UpperCAmelCase__ = outputs.reshaped_hidden_states self.assertEqual(len(__a ) , __a ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = reshaped_hidden_states[0].shape UpperCAmelCase__ = ( reshaped_hidden_states[0].view(__a , __a , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: UpperCAmelCase__ = True self.check_hidden_states_output(__a , __a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ = True self.check_hidden_states_output(__a , __a , __a , __a ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ = 3 UpperCAmelCase__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCAmelCase__ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCAmelCase__ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCAmelCase__ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: UpperCAmelCase__ = True self.check_hidden_states_output(__a , __a , __a , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ = True self.check_hidden_states_output(__a , __a , __a , (padded_height, padded_width) ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a ) def UpperCamelCase__ (self ) -> str: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def UpperCamelCase__ (self ) -> Dict: """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ = SwinvaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ = _config_zero_init(__a ) for model_class in self.all_model_classes: UpperCAmelCase__ = model_class(config=__a ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: 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" , ) @require_vision @require_torch class lowercase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( __a ) UpperCAmelCase__ = self.default_image_processor UpperCAmelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) UpperCAmelCase__ = image_processor(images=__a , return_tensors='pt' ).to(__a ) # forward pass with torch.no_grad(): UpperCAmelCase__ = model(**__a ) # verify the logits UpperCAmelCase__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) UpperCAmelCase__ = torch.tensor([-0.39_47, -0.43_06, 0.00_26] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4 ) )
335
1
import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( 'kwargs, expected' , [ ({'num_shards': 0, 'max_num_jobs': 1}, []), ({'num_shards': 10, 'max_num_jobs': 1}, [range(10 )]), ({'num_shards': 10, 'max_num_jobs': 10}, [range(snake_case__ , i + 1 ) for i in range(10 )]), ({'num_shards': 1, 'max_num_jobs': 10}, [range(1 )]), ({'num_shards': 10, 'max_num_jobs': 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({'num_shards': 3, 'max_num_jobs': 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCamelCase_( snake_case__: Union[str, Any] , snake_case__: Any ) -> Any: UpperCAmelCase__ = _distribute_shards(**snake_case__ ) assert out == expected @pytest.mark.parametrize( 'gen_kwargs, max_num_jobs, expected' , [ ({'foo': 0}, 10, [{'foo': 0}]), ({'shards': [0, 1, 2, 3]}, 1, [{'shards': [0, 1, 2, 3]}]), ({'shards': [0, 1, 2, 3]}, 4, [{'shards': [0]}, {'shards': [1]}, {'shards': [2]}, {'shards': [3]}]), ({'shards': [0, 1]}, 4, [{'shards': [0]}, {'shards': [1]}]), ({'shards': [0, 1, 2, 3]}, 2, [{'shards': [0, 1]}, {'shards': [2, 3]}]), ] , ) def UpperCamelCase_( snake_case__: Any , snake_case__: Tuple , snake_case__: str ) -> List[str]: UpperCAmelCase__ = _split_gen_kwargs(snake_case__ , snake_case__ ) assert out == expected @pytest.mark.parametrize( 'gen_kwargs, expected' , [ ({'foo': 0}, 1), ({'shards': [0]}, 1), ({'shards': [0, 1, 2, 3]}, 4), ({'shards': [0, 1, 2, 3], 'foo': 0}, 4), ({'shards': [0, 1, 2, 3], 'other': (0, 1)}, 4), ({'shards': [0, 1, 2, 3], 'shards2': [0, 1]}, RuntimeError), ] , ) def UpperCamelCase_( snake_case__: Dict , snake_case__: Any ) -> int: if expected is RuntimeError: with pytest.raises(snake_case__ ): _number_of_shards_in_gen_kwargs(snake_case__ ) else: UpperCAmelCase__ = _number_of_shards_in_gen_kwargs(snake_case__ ) assert out == expected
335
from collections import deque def UpperCamelCase_( snake_case__: Tuple ) -> Tuple: UpperCAmelCase__ = len(snake_case__ ) UpperCAmelCase__ = deque() UpperCAmelCase__ = [False for _ in range(snake_case__ )] UpperCAmelCase__ = [-1 for _ in range(snake_case__ )] UpperCAmelCase__ = index_of[:] def strong_connect(snake_case__: List[str] , snake_case__: List[str] , snake_case__: List[str] ): UpperCAmelCase__ = index # the number when this node is seen UpperCAmelCase__ = index # lowest rank node reachable from here index += 1 stack.append(snake_case__ ) UpperCAmelCase__ = True for w in g[v]: if index_of[w] == -1: UpperCAmelCase__ = strong_connect(snake_case__ , snake_case__ , snake_case__ ) UpperCAmelCase__ = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: UpperCAmelCase__ = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: UpperCAmelCase__ = [] UpperCAmelCase__ = stack.pop() UpperCAmelCase__ = False component.append(snake_case__ ) while w != v: UpperCAmelCase__ = stack.pop() UpperCAmelCase__ = False component.append(snake_case__ ) components.append(snake_case__ ) return index UpperCAmelCase__ = [] for v in range(snake_case__ ): if index_of[v] == -1: strong_connect(snake_case__ , 0 , snake_case__ ) return components def UpperCamelCase_( snake_case__: Dict , snake_case__: List[Any] ) -> Optional[int]: UpperCAmelCase__ = [[] for _ in range(snake_case__ )] for u, v in edges: g[u].append(snake_case__ ) return g if __name__ == "__main__": # Test _UpperCamelCase = 7 _UpperCamelCase = [0, 0, 1, 2, 3, 3, 4, 4, 6] _UpperCamelCase = [1, 3, 2, 0, 1, 4, 5, 6, 5] _UpperCamelCase = [(u, v) for u, v in zip(source, target)] _UpperCamelCase = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
335
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCamelCase = { '''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: _UpperCamelCase = [ '''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 _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
335
from ...configuration_utils import PretrainedConfig _UpperCamelCase = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class lowercase ( _UpperCamelCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = """tapas""" def __init__(self , __a=30522 , __a=768 , __a=12 , __a=12 , __a=3072 , __a="gelu" , __a=0.1 , __a=0.1 , __a=1024 , __a=[3, 256, 256, 2, 256, 256, 10] , __a=0.02 , __a=1E-1_2 , __a=0 , __a=10.0 , __a=0 , __a=1.0 , __a=None , __a=1.0 , __a=False , __a=None , __a=1.0 , __a=1.0 , __a=False , __a=False , __a="ratio" , __a=None , __a=None , __a=64 , __a=32 , __a=False , __a=True , __a=False , __a=False , __a=True , __a=False , __a=None , __a=None , **__a , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=__a , **__a ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = hidden_act UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_sizes UpperCAmelCase__ = initializer_range UpperCAmelCase__ = layer_norm_eps # Fine-tuning task hyperparameters UpperCAmelCase__ = positive_label_weight UpperCAmelCase__ = num_aggregation_labels UpperCAmelCase__ = aggregation_loss_weight UpperCAmelCase__ = use_answer_as_supervision UpperCAmelCase__ = answer_loss_importance UpperCAmelCase__ = use_normalized_answer_loss UpperCAmelCase__ = huber_loss_delta UpperCAmelCase__ = temperature UpperCAmelCase__ = aggregation_temperature UpperCAmelCase__ = use_gumbel_for_cells UpperCAmelCase__ = use_gumbel_for_aggregation UpperCAmelCase__ = average_approximation_function UpperCAmelCase__ = cell_selection_preference UpperCAmelCase__ = answer_loss_cutoff UpperCAmelCase__ = max_num_rows UpperCAmelCase__ = max_num_columns UpperCAmelCase__ = average_logits_per_cell UpperCAmelCase__ = select_one_column UpperCAmelCase__ = allow_empty_column_selection UpperCAmelCase__ = init_cell_selection_weights_to_zero UpperCAmelCase__ = reset_position_index_per_cell UpperCAmelCase__ = disable_per_token_loss # Aggregation hyperparameters UpperCAmelCase__ = aggregation_labels UpperCAmelCase__ = no_aggregation_label_index if isinstance(self.aggregation_labels , __a ): UpperCAmelCase__ = {int(__a ): v for k, v in aggregation_labels.items()}
335
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): _UpperCamelCase = '''pt''' elif is_tf_available(): _UpperCamelCase = '''tf''' else: _UpperCamelCase = '''jax''' class lowercase ( _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ByTaTokenizer __SCREAMING_SNAKE_CASE = False def UpperCamelCase__ (self ) -> Dict: """simple docstring""" super().setUp() UpperCAmelCase__ = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" return ByTaTokenizer.from_pretrained('google/byt5-small' ) def UpperCamelCase__ (self , **__a ) -> ByTaTokenizer: """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **__a ) def UpperCamelCase__ (self , __a , __a=False , __a=20 , __a=5 ) -> Tuple[str, list]: """simple docstring""" UpperCAmelCase__ = [] for i in range(len(__a ) ): try: UpperCAmelCase__ = tokenizer.decode([i] , clean_up_tokenization_spaces=__a ) except UnicodeDecodeError: pass toks.append((i, tok) ) UpperCAmelCase__ = list(filter(lambda __a : re.match(r'^[ a-zA-Z]+$' , t[1] ) , __a ) ) UpperCAmelCase__ = list(filter(lambda __a : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=__a ) , __a ) ) if max_length is not None and len(__a ) > max_length: UpperCAmelCase__ = toks[:max_length] if min_length is not None and len(__a ) < min_length and len(__a ) > 0: while len(__a ) < min_length: UpperCAmelCase__ = toks + toks # toks_str = [t[1] for t in toks] UpperCAmelCase__ = [t[0] for t in toks] # Ensure consistency UpperCAmelCase__ = tokenizer.decode(__a , clean_up_tokenization_spaces=__a ) if " " not in output_txt and len(__a ) > 1: UpperCAmelCase__ = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__a ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__a ) ) if with_prefix_space: UpperCAmelCase__ = ' ' + output_txt UpperCAmelCase__ = tokenizer.encode(__a , add_special_tokens=__a ) return output_txt, output_ids def UpperCamelCase__ (self ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.ta_base_tokenizer UpperCAmelCase__ = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) UpperCAmelCase__ = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def UpperCamelCase__ (self ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.ta_base_tokenizer UpperCAmelCase__ = 'Unicode €.' UpperCAmelCase__ = tokenizer(__a ) UpperCAmelCase__ = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['input_ids'] , __a ) # decoding UpperCAmelCase__ = tokenizer.decode(__a ) self.assertEqual(__a , 'Unicode €.</s>' ) UpperCAmelCase__ = tokenizer('e è é ê ë' ) UpperCAmelCase__ = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['input_ids'] , __a ) # decoding UpperCAmelCase__ = tokenizer.decode(__a ) self.assertEqual(__a , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def UpperCamelCase__ (self ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.ta_base_tokenizer UpperCAmelCase__ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off UpperCAmelCase__ = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on UpperCAmelCase__ = tokenizer(__a , padding=__a , return_tensors=__a ) self.assertIsInstance(__a , __a ) if FRAMEWORK != "jax": UpperCAmelCase__ = list(batch.input_ids.numpy()[0] ) else: UpperCAmelCase__ = list(batch.input_ids.tolist()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = self.ta_base_tokenizer UpperCAmelCase__ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] UpperCAmelCase__ = tokenizer(__a , padding=__a , return_tensors=__a ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , __a ) self.assertIn('attention_mask' , __a ) self.assertNotIn('decoder_input_ids' , __a ) self.assertNotIn('decoder_attention_mask' , __a ) def UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.ta_base_tokenizer UpperCAmelCase__ = [ 'Summary of the text.', 'Another summary.', ] UpperCAmelCase__ = tokenizer( text_target=__a , max_length=32 , padding='max_length' , truncation=__a , return_tensors=__a ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.ta_base_tokenizer UpperCAmelCase__ = ['A long paragraph for summarization. </s>'] UpperCAmelCase__ = ['Summary of the text. </s>'] # fmt: off UpperCAmelCase__ = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] UpperCAmelCase__ = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on UpperCAmelCase__ = tokenizer(__a , text_target=__a ) self.assertEqual(__a , batch['input_ids'][0] ) self.assertEqual(__a , batch['labels'][0] ) def UpperCamelCase__ (self ) -> Any: """simple docstring""" UpperCAmelCase__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test UpperCAmelCase__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc UpperCAmelCase__ = tempfile.mkdtemp() UpperCAmelCase__ = ' He is very happy, UNwant\u00E9d,running' UpperCAmelCase__ = tokenizer.encode(__a , add_special_tokens=__a ) tokenizer.save_pretrained(__a ) UpperCAmelCase__ = tokenizer.__class__.from_pretrained(__a ) UpperCAmelCase__ = after_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) shutil.rmtree(__a ) UpperCAmelCase__ = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc UpperCAmelCase__ = tempfile.mkdtemp() UpperCAmelCase__ = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) UpperCAmelCase__ = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) UpperCAmelCase__ = tokenizer.encode(__a , add_special_tokens=__a ) tokenizer.save_pretrained(__a ) UpperCAmelCase__ = tokenizer.__class__.from_pretrained(__a ) UpperCAmelCase__ = after_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) UpperCAmelCase__ = tokenizer.__class__.from_pretrained(__a , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(__a ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__a ) with open(os.path.join(__a , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: UpperCAmelCase__ = json.load(__a ) with open(os.path.join(__a , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: UpperCAmelCase__ = json.load(__a ) UpperCAmelCase__ = [F"<extra_id_{i}>" for i in range(125 )] UpperCAmelCase__ = added_tokens_extra_ids + [ 'an_additional_special_token' ] UpperCAmelCase__ = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(__a , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(__a , __a ) with open(os.path.join(__a , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(__a , __a ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files UpperCAmelCase__ = tokenizer_class.from_pretrained( __a , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained UpperCAmelCase__ = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=__a )] UpperCAmelCase__ = tokenizer_class.from_pretrained( __a , additional_special_tokens=__a , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def UpperCamelCase__ (self ) -> Any: """simple docstring""" UpperCAmelCase__ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__a ) UpperCAmelCase__ = tokenizer_class.from_pretrained(__a ) self.assertTrue(tokenizer.decode([255] ) == '' ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" pass def UpperCamelCase__ (self ) -> str: """simple docstring""" pass def UpperCamelCase__ (self ) -> str: """simple docstring""" pass def UpperCamelCase__ (self ) -> Dict: """simple docstring""" pass def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.get_tokenizers(fast=__a , do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): UpperCAmelCase__ = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] UpperCAmelCase__ = tokenizer.convert_tokens_to_string(__a ) self.assertIsInstance(__a , __a ) def UpperCamelCase__ (self ) -> Any: """simple docstring""" UpperCAmelCase__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): UpperCAmelCase__ = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] UpperCAmelCase__ = 0 UpperCAmelCase__ = tokenizer.convert_ids_to_tokens( __a , skip_special_tokens=__a ) for attr in attributes_list: setattr(__a , attr + '_id' , __a ) self.assertEqual(getattr(__a , __a ) , __a ) self.assertEqual(getattr(__a , attr + '_id' ) , __a ) setattr(__a , attr + '_id' , __a ) self.assertEqual(getattr(__a , __a ) , __a ) self.assertEqual(getattr(__a , attr + '_id' ) , __a ) setattr(__a , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(__a , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(__a , 'additional_special_tokens_ids' ) , [] ) setattr(__a , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(__a , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(__a , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
335
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCamelCase = { '''configuration_squeezebert''': [ '''SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SqueezeBertConfig''', '''SqueezeBertOnnxConfig''', ], '''tokenization_squeezebert''': ['''SqueezeBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''SqueezeBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SqueezeBertForMaskedLM''', '''SqueezeBertForMultipleChoice''', '''SqueezeBertForQuestionAnswering''', '''SqueezeBertForSequenceClassification''', '''SqueezeBertForTokenClassification''', '''SqueezeBertModel''', '''SqueezeBertModule''', '''SqueezeBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
335
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { '''microsoft/swin-tiny-patch4-window7-224''': ( '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json''' ), # See all Swin models at https://huggingface.co/models?filter=swin } class lowercase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = """swin""" __SCREAMING_SNAKE_CASE = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__(self , __a=224 , __a=4 , __a=3 , __a=96 , __a=[2, 2, 6, 2] , __a=[3, 6, 12, 24] , __a=7 , __a=4.0 , __a=True , __a=0.0 , __a=0.0 , __a=0.1 , __a="gelu" , __a=False , __a=0.02 , __a=1E-5 , __a=32 , __a=None , __a=None , **__a , ) -> Optional[int]: """simple docstring""" super().__init__(**__a ) UpperCAmelCase__ = image_size UpperCAmelCase__ = patch_size UpperCAmelCase__ = num_channels UpperCAmelCase__ = embed_dim UpperCAmelCase__ = depths UpperCAmelCase__ = len(__a ) UpperCAmelCase__ = num_heads UpperCAmelCase__ = window_size UpperCAmelCase__ = mlp_ratio UpperCAmelCase__ = qkv_bias UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = drop_path_rate UpperCAmelCase__ = hidden_act UpperCAmelCase__ = use_absolute_embeddings UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = initializer_range UpperCAmelCase__ = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model UpperCAmelCase__ = int(embed_dim * 2 ** (len(__a ) - 1) ) UpperCAmelCase__ = ['stem'] + [F"stage{idx}" for idx in range(1 , len(__a ) + 1 )] UpperCAmelCase__ , UpperCAmelCase__ = get_aligned_output_features_output_indices( out_features=__a , out_indices=__a , stage_names=self.stage_names ) class lowercase ( _UpperCamelCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = version.parse("""1.11""" ) @property def UpperCamelCase__ (self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def UpperCamelCase__ (self ) -> float: """simple docstring""" return 1E-4
335
import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def UpperCamelCase_( snake_case__: Union[str, Any] , snake_case__: Union[str, Any] ) -> Union[str, Any]: UpperCAmelCase__ = XCLIPTextConfig() # derive patch size from model name UpperCAmelCase__ = model_name.find('patch' ) UpperCAmelCase__ = int(model_name[start_idx + len('patch' ) : start_idx + len('patch' ) + 2] ) UpperCAmelCase__ = XCLIPVisionConfig(patch_size=snake_case__ , num_frames=snake_case__ ) if "large" in model_name: UpperCAmelCase__ = 7_68 UpperCAmelCase__ = 30_72 UpperCAmelCase__ = 12 UpperCAmelCase__ = 10_24 UpperCAmelCase__ = 40_96 UpperCAmelCase__ = 16 UpperCAmelCase__ = 24 UpperCAmelCase__ = 7_68 UpperCAmelCase__ = 30_72 if model_name == "xclip-large-patch14-16-frames": UpperCAmelCase__ = 3_36 UpperCAmelCase__ = XCLIPConfig.from_text_vision_configs(snake_case__ , snake_case__ ) if "large" in model_name: UpperCAmelCase__ = 7_68 return config def UpperCamelCase_( snake_case__: Any ) -> Tuple: # text encoder if name == "token_embedding.weight": UpperCAmelCase__ = name.replace('token_embedding.weight' , 'text_model.embeddings.token_embedding.weight' ) if name == "positional_embedding": UpperCAmelCase__ = name.replace('positional_embedding' , 'text_model.embeddings.position_embedding.weight' ) if "ln_1" in name: UpperCAmelCase__ = name.replace('ln_1' , 'layer_norm1' ) if "ln_2" in name: UpperCAmelCase__ = name.replace('ln_2' , 'layer_norm2' ) if "c_fc" in name: UpperCAmelCase__ = name.replace('c_fc' , 'fc1' ) if "c_proj" in name: UpperCAmelCase__ = name.replace('c_proj' , 'fc2' ) if name.startswith('transformer.resblocks' ): UpperCAmelCase__ = name.replace('transformer.resblocks' , 'text_model.encoder.layers' ) if "attn.out_proj" in name and "message" not in name: UpperCAmelCase__ = name.replace('attn.out_proj' , 'self_attn.out_proj' ) if "ln_final" in name: UpperCAmelCase__ = name.replace('ln_final' , 'text_model.final_layer_norm' ) # visual encoder if name == "visual.class_embedding": UpperCAmelCase__ = name.replace('visual.class_embedding' , 'vision_model.embeddings.class_embedding' ) if name == "visual.positional_embedding": UpperCAmelCase__ = name.replace('visual.positional_embedding' , 'vision_model.embeddings.position_embedding.weight' ) if name.startswith('visual.transformer.resblocks' ): UpperCAmelCase__ = name.replace('visual.transformer.resblocks' , 'vision_model.encoder.layers' ) if "visual.conv1" in name: UpperCAmelCase__ = name.replace('visual.conv1' , 'vision_model.embeddings.patch_embedding' ) if "visual.ln_pre" in name: UpperCAmelCase__ = name.replace('visual.ln_pre' , 'vision_model.pre_layernorm' ) if "visual.ln_post" in name: UpperCAmelCase__ = name.replace('visual.ln_post' , 'vision_model.post_layernorm' ) if "visual.proj" in name: UpperCAmelCase__ = name.replace('visual.proj' , 'visual_projection.weight' ) if "text_projection" in name: UpperCAmelCase__ = name.replace('text_projection' , 'text_projection.weight' ) # things on top if "prompts_visual_proj" in name: UpperCAmelCase__ = name.replace('prompts_visual_proj' , 'prompts_visual_projection' ) if "prompts_visual_ln" in name: UpperCAmelCase__ = name.replace('prompts_visual_ln' , 'prompts_visual_layernorm' ) # mit if name == "mit.positional_embedding": UpperCAmelCase__ = name.replace('positional' , 'position' ) if name.startswith('mit.resblocks' ): UpperCAmelCase__ = name.replace('mit.resblocks' , 'mit.encoder.layers' ) # prompts generator if name.startswith('prompts_generator.norm' ): UpperCAmelCase__ = name.replace('prompts_generator.norm' , 'prompts_generator.layernorm' ) return name def UpperCamelCase_( snake_case__: Union[str, Any] , snake_case__: List[Any] ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): UpperCAmelCase__ = orig_state_dict.pop(snake_case__ ) if "attn.in_proj" in key: UpperCAmelCase__ = key.split('.' ) if key.startswith('visual' ): UpperCAmelCase__ = key_split[3] UpperCAmelCase__ = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: UpperCAmelCase__ = val[ :dim, : ] UpperCAmelCase__ = val[ dim : dim * 2, : ] UpperCAmelCase__ = val[ -dim:, : ] else: UpperCAmelCase__ = val[ :dim ] UpperCAmelCase__ = val[ dim : dim * 2 ] UpperCAmelCase__ = val[ -dim: ] else: if "weight" in key: UpperCAmelCase__ = val[ :dim, : ] UpperCAmelCase__ = val[ dim : dim * 2, : ] UpperCAmelCase__ = val[ -dim:, : ] else: UpperCAmelCase__ = val[:dim] UpperCAmelCase__ = val[ dim : dim * 2 ] UpperCAmelCase__ = val[-dim:] elif key.startswith('mit' ): UpperCAmelCase__ = key_split[2] UpperCAmelCase__ = config.vision_config.mit_hidden_size if "weight" in key: UpperCAmelCase__ = val[:dim, :] UpperCAmelCase__ = val[dim : dim * 2, :] UpperCAmelCase__ = val[-dim:, :] else: UpperCAmelCase__ = val[:dim] UpperCAmelCase__ = val[dim : dim * 2] UpperCAmelCase__ = val[-dim:] else: UpperCAmelCase__ = key_split[2] UpperCAmelCase__ = config.text_config.hidden_size if "weight" in key: UpperCAmelCase__ = val[:dim, :] UpperCAmelCase__ = val[ dim : dim * 2, : ] UpperCAmelCase__ = val[-dim:, :] else: UpperCAmelCase__ = val[:dim] UpperCAmelCase__ = val[ dim : dim * 2 ] UpperCAmelCase__ = val[-dim:] else: UpperCAmelCase__ = rename_key(snake_case__ ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: UpperCAmelCase__ = val.T UpperCAmelCase__ = val return orig_state_dict def UpperCamelCase_( snake_case__: Tuple ) -> Optional[Any]: if num_frames == 8: UpperCAmelCase__ = 'eating_spaghetti_8_frames.npy' elif num_frames == 16: UpperCAmelCase__ = 'eating_spaghetti.npy' elif num_frames == 32: UpperCAmelCase__ = 'eating_spaghetti_32_frames.npy' UpperCAmelCase__ = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename=snake_case__ , repo_type='dataset' , ) UpperCAmelCase__ = np.load(snake_case__ ) return list(snake_case__ ) def UpperCamelCase_( snake_case__: Tuple , snake_case__: str=None , snake_case__: Union[str, Any]=False ) -> List[Any]: UpperCAmelCase__ = { # fully supervised kinetics-400 checkpoints 'xclip-base-patch32': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth', 'xclip-base-patch32-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth' ), 'xclip-base-patch16': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth', 'xclip-base-patch16-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth' ), 'xclip-large-patch14': 'https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb', 'xclip-large-patch14-16-frames': 'https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f', # fully supervised kinetics-600 checkpoints 'xclip-base-patch16-kinetics-600': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth' ), 'xclip-base-patch16-kinetics-600-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth' ), 'xclip-large-patch14-kinetics-600': 'https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be', # few shot 'xclip-base-patch16-hmdb-2-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth' ), 'xclip-base-patch16-hmdb-4-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth' ), 'xclip-base-patch16-hmdb-8-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth' ), 'xclip-base-patch16-hmdb-16-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth' ), 'xclip-base-patch16-ucf-2-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth' ), 'xclip-base-patch16-ucf-4-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth' ), 'xclip-base-patch16-ucf-8-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth' ), 'xclip-base-patch16-ucf-16-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth' ), # zero shot 'xclip-base-patch16-zero-shot': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth', } UpperCAmelCase__ = model_to_url[model_name] UpperCAmelCase__ = 8 if "16-frames" in model_name: UpperCAmelCase__ = 16 elif "shot" in model_name: UpperCAmelCase__ = 32 UpperCAmelCase__ = get_xclip_config(snake_case__ , snake_case__ ) UpperCAmelCase__ = XCLIPModel(snake_case__ ) model.eval() if "drive" in checkpoint_url: UpperCAmelCase__ = 'pytorch_model.bin' gdown.cached_download(snake_case__ , snake_case__ , quiet=snake_case__ ) UpperCAmelCase__ = torch.load(snake_case__ , map_location='cpu' )['model'] else: UpperCAmelCase__ = torch.hub.load_state_dict_from_url(snake_case__ )['model'] UpperCAmelCase__ = convert_state_dict(snake_case__ , snake_case__ ) UpperCAmelCase__ = XCLIPModel(snake_case__ ) UpperCAmelCase__ , UpperCAmelCase__ = model.load_state_dict(snake_case__ , strict=snake_case__ ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() UpperCAmelCase__ = 3_36 if model_name == 'xclip-large-patch14-16-frames' else 2_24 UpperCAmelCase__ = VideoMAEImageProcessor(size=snake_case__ ) UpperCAmelCase__ = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32' ) UpperCAmelCase__ = CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32' ) UpperCAmelCase__ = XCLIPProcessor(image_processor=snake_case__ , tokenizer=snake_case__ ) UpperCAmelCase__ = prepare_video(snake_case__ ) UpperCAmelCase__ = processor( text=['playing sports', 'eating spaghetti', 'go shopping'] , videos=snake_case__ , return_tensors='pt' , padding=snake_case__ ) print('Shape of pixel values:' , inputs.pixel_values.shape ) with torch.no_grad(): UpperCAmelCase__ = model(**snake_case__ ) # Verify outputs UpperCAmelCase__ = outputs.logits_per_video UpperCAmelCase__ = logits_per_video.softmax(dim=1 ) print('Probs:' , snake_case__ ) # kinetics-400 if model_name == "xclip-base-patch32": UpperCAmelCase__ = torch.tensor([[0.0_0_1_9, 0.9_9_5_1, 0.0_0_3_0]] ) elif model_name == "xclip-base-patch32-16-frames": UpperCAmelCase__ = torch.tensor([[7.0_999e-04, 9.9_883e-01, 4.5_580e-04]] ) elif model_name == "xclip-base-patch16": UpperCAmelCase__ = torch.tensor([[0.0_0_8_3, 0.9_6_8_1, 0.0_2_3_6]] ) elif model_name == "xclip-base-patch16-16-frames": UpperCAmelCase__ = torch.tensor([[7.6_937e-04, 9.9_728e-01, 1.9_473e-03]] ) elif model_name == "xclip-large-patch14": UpperCAmelCase__ = torch.tensor([[0.0_0_6_2, 0.9_8_6_4, 0.0_0_7_5]] ) elif model_name == "xclip-large-patch14-16-frames": UpperCAmelCase__ = torch.tensor([[3.3_877e-04, 9.9_937e-01, 2.8_888e-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": UpperCAmelCase__ = torch.tensor([[0.0_5_5_5, 0.8_9_1_4, 0.0_5_3_1]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": UpperCAmelCase__ = torch.tensor([[3.8_554e-04, 9.9_929e-01, 3.2_754e-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": UpperCAmelCase__ = torch.tensor([[0.0_0_3_6, 0.9_9_2_0, 0.0_0_4_5]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": UpperCAmelCase__ = torch.tensor([[7.1_890e-06, 9.9_994e-01, 5.6_559e-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": UpperCAmelCase__ = torch.tensor([[1.0_320e-05, 9.9_993e-01, 6.2_435e-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": UpperCAmelCase__ = torch.tensor([[4.1_377e-06, 9.9_990e-01, 9.8_386e-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": UpperCAmelCase__ = torch.tensor([[4.1_347e-05, 9.9_962e-01, 3.3_411e-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": UpperCAmelCase__ = torch.tensor([[8.5_857e-05, 9.9_928e-01, 6.3_291e-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": UpperCAmelCase__ = torch.tensor([[8.5_857e-05, 9.9_928e-01, 6.3_291e-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": UpperCAmelCase__ = torch.tensor([[0.0_0_2_7, 0.9_9_0_4, 0.0_0_7_0]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": UpperCAmelCase__ = torch.tensor([[9.8_219e-04, 9.9_593e-01, 3.0_863e-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": UpperCAmelCase__ = torch.tensor([[3.5_082e-04, 9.9_785e-01, 1.7_966e-03]] ) else: raise ValueError(f"Model name {model_name} not supported" ) assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case__ ) if push_to_hub: print('Pushing model, processor and slow tokenizer files to the hub...' ) model.push_to_hub(snake_case__ , organization='nielsr' ) processor.push_to_hub(snake_case__ , organization='nielsr' ) slow_tokenizer.push_to_hub(snake_case__ , organization='nielsr' ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''xclip-base-patch32''', type=str, help='''Name of the model.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _UpperCamelCase = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
335
1
class lowercase : '''simple docstring''' def __init__(self , __a ) -> Tuple: """simple docstring""" UpperCAmelCase__ = val UpperCAmelCase__ = None UpperCAmelCase__ = None def UpperCamelCase__ (self , __a ) -> Optional[Any]: """simple docstring""" if self.val: if val < self.val: if self.left is None: UpperCAmelCase__ = Node(__a ) else: self.left.insert(__a ) elif val > self.val: if self.right is None: UpperCAmelCase__ = Node(__a ) else: self.right.insert(__a ) else: UpperCAmelCase__ = val def UpperCamelCase_( snake_case__: Tuple , snake_case__: str ) -> Dict: # Recursive traversal if root: inorder(root.left , snake_case__ ) res.append(root.val ) inorder(root.right , snake_case__ ) def UpperCamelCase_( snake_case__: Optional[Any] ) -> Union[str, Any]: # Build BST if len(snake_case__ ) == 0: return arr UpperCAmelCase__ = Node(arr[0] ) for i in range(1 , len(snake_case__ ) ): root.insert(arr[i] ) # Traverse BST in order. UpperCAmelCase__ = [] inorder(snake_case__ , snake_case__ ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
335
import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def UpperCamelCase_( snake_case__: Optional[int] , snake_case__: List[Any] , snake_case__: Union[str, Any] ) -> Tuple: UpperCAmelCase__ = OmegaConf.load(snake_case__ ) UpperCAmelCase__ = torch.load(snake_case__ , map_location='cpu' )['model'] UpperCAmelCase__ = list(state_dict.keys() ) # extract state_dict for VQVAE UpperCAmelCase__ = {} UpperCAmelCase__ = 'first_stage_model.' for key in keys: if key.startswith(snake_case__ ): UpperCAmelCase__ = state_dict[key] # extract state_dict for UNetLDM UpperCAmelCase__ = {} UpperCAmelCase__ = 'model.diffusion_model.' for key in keys: if key.startswith(snake_case__ ): UpperCAmelCase__ = state_dict[key] UpperCAmelCase__ = config.model.params.first_stage_config.params UpperCAmelCase__ = config.model.params.unet_config.params UpperCAmelCase__ = VQModel(**snake_case__ ).eval() vqvae.load_state_dict(snake_case__ ) UpperCAmelCase__ = UNetLDMModel(**snake_case__ ).eval() unet.load_state_dict(snake_case__ ) UpperCAmelCase__ = DDIMScheduler( timesteps=config.model.params.timesteps , beta_schedule='scaled_linear' , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=snake_case__ , ) UpperCAmelCase__ = LDMPipeline(snake_case__ , snake_case__ , snake_case__ ) pipeline.save_pretrained(snake_case__ ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', type=str, required=True) parser.add_argument('''--config_path''', type=str, required=True) parser.add_argument('''--output_path''', type=str, required=True) _UpperCamelCase = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
335
1