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
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class __lowerCAmelCase ( SCREAMING_SNAKE_CASE ): _a = """mgp-str""" def __init__( self , lowerCAmelCase=[32, 128] , lowerCAmelCase=4 , lowerCAmelCase=3 , lowerCAmelCase=27 , lowerCAmelCase=38 , lowerCAmelCase=50_257 , lowerCAmelCase=30_522 , lowerCAmelCase=768 , lowerCAmelCase=12 , lowerCAmelCase=12 , lowerCAmelCase=4.0 , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=1e-5 , lowerCAmelCase=0.0 , lowerCAmelCase=0.0 , lowerCAmelCase=0.0 , lowerCAmelCase=False , lowerCAmelCase=0.02 , **lowerCAmelCase , ) -> Any: '''simple docstring''' super().__init__(**lowerCAmelCase ) _lowercase =image_size _lowercase =patch_size _lowercase =num_channels _lowercase =max_token_length _lowercase =num_character_labels _lowercase =num_bpe_labels _lowercase =num_wordpiece_labels _lowercase =hidden_size _lowercase =num_hidden_layers _lowercase =num_attention_heads _lowercase =mlp_ratio _lowercase =distilled _lowercase =layer_norm_eps _lowercase =drop_rate _lowercase =qkv_bias _lowercase =attn_drop_rate _lowercase =drop_path_rate _lowercase =output_aa_attentions _lowercase =initializer_range
205
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def a ( A__ : bool = True , *A__ : int , **A__ : Union[str, Any] ) -> List[str]: """simple docstring""" if not is_tqdm_available(): raise ImportError('Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.' ) _lowercase =False if main_process_only: _lowercase =PartialState().local_process_index == 0 return _tqdm(*A__ , **A__ , disable=A__ )
205
1
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> float: def get_matched_characters(__lowerCamelCase , __lowerCamelCase ) -> str: lowercase__ : List[str] = [] lowercase__ : Union[str, Any] = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): lowercase__ : Any = int(max(0 , i - limit ) ) lowercase__ : List[Any] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(__lowerCamelCase ) lowercase__ : Tuple = f"""{_stra[0:_stra.index(__lowerCamelCase )]} {_stra[_stra.index(__lowerCamelCase ) + 1:]}""" return "".join(__lowerCamelCase ) # matching characters lowercase__ : str = get_matched_characters(__lowerCamelCase , __lowerCamelCase ) lowercase__ : Dict = get_matched_characters(__lowerCamelCase , __lowerCamelCase ) lowercase__ : Union[str, Any] = len(__lowerCamelCase ) # transposition lowercase__ : List[Any] = ( len([(ca, ca) for ca, ca in zip(__lowerCamelCase , __lowerCamelCase ) if ca != ca] ) // 2 ) if not match_count: lowercase__ : Union[str, Any] = 0.0 else: lowercase__ : Any = ( 1 / 3 * ( match_count / len(__lowerCamelCase ) + match_count / len(__lowerCamelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters lowercase__ : Union[str, Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
302
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase_ = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
302
1
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } UpperCamelCase__ = { """vocab_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"""}, """merges_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"""}, """tokenizer_config_file""": { """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json""" }, } UpperCamelCase__ = {"""facebook/blenderbot-3B""": 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _a ( ): __lowerCAmelCase = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) __lowerCAmelCase = bs[:] __lowerCAmelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE_ ) cs.append(2**8 + n ) n += 1 __lowerCAmelCase = [chr(SCREAMING_SNAKE_CASE_ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): __lowerCAmelCase = set() __lowerCAmelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCAmelCase = char return pairs class a__ ( snake_case__ ): _a : str = VOCAB_FILES_NAMES _a : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _a : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a : Union[str, Any] = ["""input_ids""", """attention_mask"""] def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else bos_token __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else eos_token __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else sep_token __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else cls_token __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else unk_token __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token super().__init__( errors=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , **_A , ) with open(_A , encoding="utf-8" ) as vocab_handle: __lowerCAmelCase = json.load(_A ) __lowerCAmelCase = {v: k for k, v in self.encoder.items()} __lowerCAmelCase = errors # how to handle errors in decoding __lowerCAmelCase = bytes_to_unicode() __lowerCAmelCase = {v: k for k, v in self.byte_encoder.items()} with open(_A , encoding="utf-8" ) as merges_handle: __lowerCAmelCase = merges_handle.read().split("\n" )[1:-1] __lowerCAmelCase = [tuple(merge.split() ) for merge in bpe_merges] __lowerCAmelCase = dict(zip(_A , range(len(_A ) ) ) ) __lowerCAmelCase = {} __lowerCAmelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __lowerCAmelCase = re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return len(self.encoder ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if token in self.cache: return self.cache[token] __lowerCAmelCase = tuple(_A ) __lowerCAmelCase = get_pairs(_A ) if not pairs: return token while True: __lowerCAmelCase = min(_A , key=lambda _A : self.bpe_ranks.get(_A , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __lowerCAmelCase , __lowerCAmelCase = bigram __lowerCAmelCase = [] __lowerCAmelCase = 0 while i < len(_A ): try: __lowerCAmelCase = word.index(_A , _A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowerCAmelCase = j if word[i] == first and i < len(_A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCAmelCase = tuple(_A ) __lowerCAmelCase = new_word if len(_A ) == 1: break else: __lowerCAmelCase = get_pairs(_A ) __lowerCAmelCase = " ".join(_A ) __lowerCAmelCase = word return word def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = [] for token in re.findall(self.pat , _A ): __lowerCAmelCase = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A ).split(" " ) ) return bpe_tokens def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return self.encoder.get(_A , self.encoder.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return self.decoder.get(_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "".join(_A ) __lowerCAmelCase = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" if not os.path.isdir(_A ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCAmelCase = os.path.join( _A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __lowerCAmelCase = os.path.join( _A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(_A , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A ) + "\n" ) __lowerCAmelCase = 0 with open(_A , "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 _A : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" " Please check that the tokenizer is not corrupted!" ) __lowerCAmelCase = token_index writer.write(" ".join(_A ) + "\n" ) index += 1 return vocab_file, merge_file def __SCREAMING_SNAKE_CASE( self , _A , _A = None , _A = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) if token_ids_a is None: return [1] + ([0] * len(_A )) + [1] return [1] + ([0] * len(_A )) + [1, 1] + ([0] * len(_A )) + [1] def __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" __lowerCAmelCase = [self.sep_token_id] __lowerCAmelCase = [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 __SCREAMING_SNAKE_CASE( self , _A , _A=False , **_A ): """simple docstring""" __lowerCAmelCase = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_A ) > 0 and not text[0].isspace()): __lowerCAmelCase = " " + text return (text, kwargs) def __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" return token_ids_a + [self.eos_token_id] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(_A ) __lowerCAmelCase = " ".join(_A ) __lowerCAmelCase = self.encode(_A ) if len(_A ) > self.model_max_length: __lowerCAmelCase = input_ids[-self.model_max_length :] logger.warning(f"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" ) return input_ids
92
from queue import PriorityQueue from typing import Any import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : set , SCREAMING_SNAKE_CASE_ : set , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : PriorityQueue , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : float | int , ): for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = pass_and_relaxation( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) __lowerCAmelCase = pass_and_relaxation( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """B""": [["""E""", 1]], """C""": [["""B""", 1]], """D""": [["""C""", 1]], """F""": [["""D""", 1], ["""G""", 1]], """E""": [[None, np.inf]], """G""": [["""E""", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
92
1
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class __snake_case (_a , _a ): lowerCAmelCase__ = 1 @register_to_config def __init__( self : Any , _UpperCAmelCase : int = 1000 , _UpperCAmelCase : Optional[Union[np.ndarray, List[float]]] = None ) -> Tuple: '''simple docstring''' self.set_timesteps(_UpperCAmelCase ) # standard deviation of the initial noise distribution _lowerCAmelCase : Any = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. _lowerCAmelCase : List[Any] = 4 # running values _lowerCAmelCase : int = [] def SCREAMING_SNAKE_CASE ( self : Tuple , _UpperCAmelCase : int , _UpperCAmelCase : Union[str, torch.device] = None ) -> Tuple: '''simple docstring''' _lowerCAmelCase : str = num_inference_steps _lowerCAmelCase : Any = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] _lowerCAmelCase : List[str] = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: _lowerCAmelCase : Any = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: _lowerCAmelCase : Any = torch.sin(steps * math.pi / 2 ) ** 2 _lowerCAmelCase : Dict = (1.0 - self.betas**2) ** 0.5 _lowerCAmelCase : List[str] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] _lowerCAmelCase : Optional[int] = timesteps.to(_UpperCAmelCase ) _lowerCAmelCase : Tuple = [] def SCREAMING_SNAKE_CASE ( self : Optional[int] , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : int , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True , ) -> Union[SchedulerOutput, Tuple]: '''simple docstring''' if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) _lowerCAmelCase : Union[str, Any] = (self.timesteps == timestep).nonzero().item() _lowerCAmelCase : Union[str, Any] = timestep_index + 1 _lowerCAmelCase : List[str] = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(_UpperCAmelCase ) if len(self.ets ) == 1: _lowerCAmelCase : Union[str, Any] = self.ets[-1] elif len(self.ets ) == 2: _lowerCAmelCase : Tuple = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: _lowerCAmelCase : Optional[Any] = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: _lowerCAmelCase : Optional[int] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) _lowerCAmelCase : Tuple = self._get_prev_sample(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] , _UpperCAmelCase : torch.FloatTensor , *_UpperCAmelCase : Any , **_UpperCAmelCase : List[str] ) -> torch.FloatTensor: '''simple docstring''' return sample def SCREAMING_SNAKE_CASE ( self : List[Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : str ) -> List[Any]: '''simple docstring''' _lowerCAmelCase : List[str] = self.alphas[timestep_index] _lowerCAmelCase : Tuple = self.betas[timestep_index] _lowerCAmelCase : Tuple = self.alphas[prev_timestep_index] _lowerCAmelCase : Optional[Any] = self.betas[prev_timestep_index] _lowerCAmelCase : Tuple = (sample - sigma * ets) / max(_UpperCAmelCase , 1E-8 ) _lowerCAmelCase : List[Any] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : Dict ) -> Any: '''simple docstring''' return self.config.num_train_timesteps
159
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def _UpperCAmelCase (UpperCamelCase_ : str , UpperCamelCase_ : Tuple=None ): '''simple docstring''' _lowerCAmelCase : List[Any] = None if token is not None: _lowerCAmelCase : str = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _lowerCAmelCase : Tuple = F"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" _lowerCAmelCase : str = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ ).json() _lowerCAmelCase : Optional[Any] = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _lowerCAmelCase : List[str] = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(UpperCamelCase_ ): _lowerCAmelCase : int = requests.get(url + F"&page={i + 2}" , headers=UpperCamelCase_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(F"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def _UpperCAmelCase (UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any]=None ): '''simple docstring''' _lowerCAmelCase : Optional[int] = None if token is not None: _lowerCAmelCase : Optional[Any] = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _lowerCAmelCase : Optional[int] = F"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" _lowerCAmelCase : Optional[int] = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ ).json() _lowerCAmelCase : List[str] = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _lowerCAmelCase : List[str] = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(UpperCamelCase_ ): _lowerCAmelCase : List[str] = requests.get(url + F"&page={i + 2}" , headers=UpperCamelCase_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(F"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def _UpperCAmelCase (UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Any ): '''simple docstring''' _lowerCAmelCase : str = None if token is not None: _lowerCAmelCase : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _lowerCAmelCase : List[str] = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ , allow_redirects=UpperCamelCase_ ) _lowerCAmelCase : List[str] = result.headers["""Location"""] _lowerCAmelCase : List[Any] = requests.get(UpperCamelCase_ , allow_redirects=UpperCamelCase_ ) _lowerCAmelCase : int = os.path.join(UpperCamelCase_ , F"{artifact_name}.zip" ) with open(UpperCamelCase_ , """wb""" ) as fp: fp.write(response.content ) def _UpperCAmelCase (UpperCamelCase_ : int , UpperCamelCase_ : Optional[int]=None ): '''simple docstring''' _lowerCAmelCase : Dict = [] _lowerCAmelCase : Any = [] _lowerCAmelCase : Union[str, Any] = None with zipfile.ZipFile(UpperCamelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCamelCase_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(UpperCamelCase_ ) as f: for line in f: _lowerCAmelCase : List[str] = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _lowerCAmelCase : Union[str, Any] = line[: line.index(""": """ )] _lowerCAmelCase : Union[str, Any] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _lowerCAmelCase : Tuple = line[len("""FAILED """ ) :] failed_tests.append(UpperCamelCase_ ) elif filename == "job_name.txt": _lowerCAmelCase : str = line if len(UpperCamelCase_ ) != len(UpperCamelCase_ ): raise ValueError( F"`errors` and `failed_tests` should have the same number of elements. Got {len(UpperCamelCase_ )} for `errors` " F"and {len(UpperCamelCase_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" """ problem.""" ) _lowerCAmelCase : int = None if job_name and job_links: _lowerCAmelCase : Optional[int] = job_links.get(UpperCamelCase_ , UpperCamelCase_ ) # A list with elements of the form (line of error, error, failed test) _lowerCAmelCase : Tuple = [x + [y] + [job_link] for x, y in zip(UpperCamelCase_ , UpperCamelCase_ )] return result def _UpperCAmelCase (UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[Any]=None ): '''simple docstring''' _lowerCAmelCase : List[Any] = [] _lowerCAmelCase : List[Any] = [os.path.join(UpperCamelCase_ , UpperCamelCase_ ) for p in os.listdir(UpperCamelCase_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(UpperCamelCase_ , job_links=UpperCamelCase_ ) ) return errors def _UpperCAmelCase (UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict=None ): '''simple docstring''' _lowerCAmelCase : List[Any] = Counter() counter.update([x[1] for x in logs] ) _lowerCAmelCase : Dict = counter.most_common() _lowerCAmelCase : Dict = {} for error, count in counts: if error_filter is None or error not in error_filter: _lowerCAmelCase : Union[str, Any] = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _lowerCAmelCase : int = dict(sorted(r.items() , key=lambda UpperCamelCase_ : item[1]["count"] , reverse=UpperCamelCase_ ) ) return r def _UpperCAmelCase (UpperCamelCase_ : Tuple ): '''simple docstring''' _lowerCAmelCase : List[str] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _lowerCAmelCase : Optional[Any] = test.split("""/""" )[2] else: _lowerCAmelCase : Union[str, Any] = None return test def _UpperCAmelCase (UpperCamelCase_ : List[str] , UpperCamelCase_ : Dict=None ): '''simple docstring''' _lowerCAmelCase : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs] _lowerCAmelCase : List[str] = [x for x in logs if x[2] is not None] _lowerCAmelCase : int = {x[2] for x in logs} _lowerCAmelCase : str = {} for test in tests: _lowerCAmelCase : Union[str, Any] = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _lowerCAmelCase : List[Any] = counter.most_common() _lowerCAmelCase : Optional[int] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} _lowerCAmelCase : List[str] = sum(error_counts.values() ) if n_errors > 0: _lowerCAmelCase : int = {"""count""": n_errors, """errors""": error_counts} _lowerCAmelCase : Dict = dict(sorted(r.items() , key=lambda UpperCamelCase_ : item[1]["count"] , reverse=UpperCamelCase_ ) ) return r def _UpperCAmelCase (UpperCamelCase_ : Union[str, Any] ): '''simple docstring''' _lowerCAmelCase : Optional[int] = """| no. | error | status |""" _lowerCAmelCase : List[Any] = """|-:|:-|:-|""" _lowerCAmelCase : str = [header, sep] for error in reduced_by_error: _lowerCAmelCase : Optional[Any] = reduced_by_error[error]["""count"""] _lowerCAmelCase : int = F"| {count} | {error[:100]} | |" lines.append(UpperCamelCase_ ) return "\n".join(UpperCamelCase_ ) def _UpperCAmelCase (UpperCamelCase_ : List[str] ): '''simple docstring''' _lowerCAmelCase : str = """| model | no. of errors | major error | count |""" _lowerCAmelCase : Any = """|-:|-:|-:|-:|""" _lowerCAmelCase : str = [header, sep] for model in reduced_by_model: _lowerCAmelCase : Union[str, Any] = reduced_by_model[model]["""count"""] _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = list(reduced_by_model[model]["""errors"""].items() )[0] _lowerCAmelCase : str = F"| {model} | {count} | {error[:60]} | {_count} |" lines.append(UpperCamelCase_ ) return "\n".join(UpperCamelCase_ ) if __name__ == "__main__": _lowerCamelCase : str = 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.") _lowerCamelCase : Tuple = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _lowerCamelCase : Optional[int] = get_job_links(args.workflow_run_id, token=args.token) _lowerCamelCase : int = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _lowerCamelCase : Optional[Any] = k.find(" / ") _lowerCamelCase : Tuple = k[index + len(" / ") :] _lowerCamelCase : List[Any] = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _lowerCamelCase : Union[str, Any] = 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) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _lowerCamelCase : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _lowerCamelCase : Dict = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _lowerCamelCase : Union[str, Any] = counter.most_common(3_0) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _lowerCamelCase : str = reduce_by_error(errors) _lowerCamelCase : Tuple = reduce_by_model(errors) _lowerCamelCase : List[str] = make_github_table(reduced_by_error) _lowerCamelCase : Optional[Any] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
159
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 A__ = logging.get_logger(__name__) A__ = { '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''', '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class a ( __lowerCamelCase ): __lowerCAmelCase : Tuple = """mobilenet_v1""" def __init__( self :Optional[Any] ,__lowercase :Dict=3 ,__lowercase :Optional[Any]=2_2_4 ,__lowercase :Any=1.0 ,__lowercase :Any=8 ,__lowercase :List[Any]="relu6" ,__lowercase :Any=True ,__lowercase :int=0.999 ,__lowercase :Optional[Any]=0.02 ,__lowercase :Optional[int]=0.001 ,**__lowercase :str ,): super().__init__(**__lowercase ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) snake_case__ : Tuple = num_channels snake_case__ : Tuple = image_size snake_case__ : List[Any] = depth_multiplier snake_case__ : List[Any] = min_depth snake_case__ : Tuple = hidden_act snake_case__ : int = tf_padding snake_case__ : Union[str, Any] = classifier_dropout_prob snake_case__ : List[str] = initializer_range snake_case__ : List[Any] = layer_norm_eps class a ( __lowerCamelCase ): __lowerCAmelCase : Any = version.parse("""1.11""" ) @property def __lowerCamelCase ( self :Tuple ): return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __lowerCamelCase ( self :List[Any] ): if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __lowerCamelCase ( self :Optional[int] ): return 1e-4
230
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = [ '''CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CTRLForSequenceClassification''', '''CTRLLMHeadModel''', '''CTRLModel''', '''CTRLPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = [ '''TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCTRLForSequenceClassification''', '''TFCTRLLMHeadModel''', '''TFCTRLModel''', '''TFCTRLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys A__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
230
1
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class a__ ( SCREAMING_SNAKE_CASE__ ): _lowerCamelCase = 42 class a__ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): _lowerCamelCase = True @register_to_config def __init__( self : Tuple, lowerCAmelCase : int = 3, lowerCAmelCase : int = 3, lowerCAmelCase : Tuple[str] = ("DownEncoderBlock2D",), lowerCAmelCase : Tuple[str] = ("UpDecoderBlock2D",), lowerCAmelCase : Tuple[int] = (64,), lowerCAmelCase : int = 1, lowerCAmelCase : str = "silu", lowerCAmelCase : int = 4, lowerCAmelCase : int = 32, lowerCAmelCase : int = 32, lowerCAmelCase : float = 0.1_8215, ) -> List[Any]: super().__init__() # pass init params to Encoder lowercase : Any = Encoder( in_channels=lowerCAmelCase, out_channels=lowerCAmelCase, down_block_types=lowerCAmelCase, block_out_channels=lowerCAmelCase, layers_per_block=lowerCAmelCase, act_fn=lowerCAmelCase, norm_num_groups=lowerCAmelCase, double_z=lowerCAmelCase, ) # pass init params to Decoder lowercase : int = Decoder( in_channels=lowerCAmelCase, out_channels=lowerCAmelCase, up_block_types=lowerCAmelCase, block_out_channels=lowerCAmelCase, layers_per_block=lowerCAmelCase, norm_num_groups=lowerCAmelCase, act_fn=lowerCAmelCase, ) lowercase : Optional[int] = nn.Convad(2 * latent_channels, 2 * latent_channels, 1 ) lowercase : Tuple = nn.Convad(lowerCAmelCase, lowerCAmelCase, 1 ) lowercase : Any = False lowercase : List[Any] = False # only relevant if vae tiling is enabled lowercase : Optional[int] = self.config.sample_size lowercase : Any = ( self.config.sample_size[0] if isinstance(self.config.sample_size, (list, tuple) ) else self.config.sample_size ) lowercase : Optional[int] = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) lowercase : Union[str, Any] = 0.25 def lowercase ( self : int, lowerCAmelCase : Optional[int], lowerCAmelCase : Any=False ) -> Any: if isinstance(lowerCAmelCase, (Encoder, Decoder) ): lowercase : int = value def lowercase ( self : int, lowerCAmelCase : bool = True ) -> Dict: lowercase : List[Any] = use_tiling def lowercase ( self : Dict ) -> int: self.enable_tiling(lowerCAmelCase ) def lowercase ( self : List[Any] ) -> List[str]: lowercase : str = True def lowercase ( self : Tuple ) -> str: lowercase : List[str] = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def lowercase ( self : Union[str, Any] ) -> Dict[str, AttentionProcessor]: lowercase : List[Any] = {} def fn_recursive_add_processors(lowerCAmelCase : str, lowerCAmelCase : torch.nn.Module, lowerCAmelCase : Dict[str, AttentionProcessor] ): if hasattr(lowerCAmelCase, 'set_processor' ): lowercase : Any = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'''{name}.{sub_name}''', lowerCAmelCase, lowerCAmelCase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) return processors def lowercase ( self : Optional[Any], lowerCAmelCase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ) -> Optional[int]: lowercase : List[str] = len(self.attn_processors.keys() ) if isinstance(lowerCAmelCase, lowerCAmelCase ) and len(lowerCAmelCase ) != count: raise ValueError( f'''A dict of processors was passed, but the number of processors {len(lowerCAmelCase )} does not match the''' f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(lowerCAmelCase : str, lowerCAmelCase : torch.nn.Module, lowerCAmelCase : Optional[Any] ): if hasattr(lowerCAmelCase, 'set_processor' ): if not isinstance(lowerCAmelCase, lowerCAmelCase ): module.set_processor(lowerCAmelCase ) else: module.set_processor(processor.pop(f'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'''{name}.{sub_name}''', lowerCAmelCase, lowerCAmelCase ) for name, module in self.named_children(): fn_recursive_attn_processor(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) def lowercase ( self : Dict ) -> List[str]: self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def lowercase ( self : int, lowerCAmelCase : torch.FloatTensor, lowerCAmelCase : bool = True ) -> AutoencoderKLOutput: if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(lowerCAmelCase, return_dict=lowerCAmelCase ) if self.use_slicing and x.shape[0] > 1: lowercase : Union[str, Any] = [self.encoder(lowerCAmelCase ) for x_slice in x.split(1 )] lowercase : str = torch.cat(lowerCAmelCase ) else: lowercase : List[Any] = self.encoder(lowerCAmelCase ) lowercase : Optional[Any] = self.quant_conv(lowerCAmelCase ) lowercase : Dict = DiagonalGaussianDistribution(lowerCAmelCase ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=lowerCAmelCase ) def lowercase ( self : Union[str, Any], lowerCAmelCase : torch.FloatTensor, lowerCAmelCase : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(lowerCAmelCase, return_dict=lowerCAmelCase ) lowercase : Tuple = self.post_quant_conv(lowerCAmelCase ) lowercase : int = self.decoder(lowerCAmelCase ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase ) @apply_forward_hook def lowercase ( self : str, lowerCAmelCase : torch.FloatTensor, lowerCAmelCase : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: if self.use_slicing and z.shape[0] > 1: lowercase : Any = [self._decode(lowerCAmelCase ).sample for z_slice in z.split(1 )] lowercase : Any = torch.cat(lowerCAmelCase ) else: lowercase : str = self._decode(lowerCAmelCase ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=lowerCAmelCase ) def lowercase ( self : Optional[int], lowerCAmelCase : str, lowerCAmelCase : Union[str, Any], lowerCAmelCase : Tuple ) -> str: lowercase : List[str] = min(a.shape[2], b.shape[2], lowerCAmelCase ) for y in range(lowerCAmelCase ): lowercase : Any = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def lowercase ( self : str, lowerCAmelCase : Optional[int], lowerCAmelCase : str, lowerCAmelCase : str ) -> Optional[int]: lowercase : Dict = min(a.shape[3], b.shape[3], lowerCAmelCase ) for x in range(lowerCAmelCase ): lowercase : str = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def lowercase ( self : Optional[int], lowerCAmelCase : torch.FloatTensor, lowerCAmelCase : bool = True ) -> AutoencoderKLOutput: lowercase : Optional[int] = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) lowercase : str = int(self.tile_latent_min_size * self.tile_overlap_factor ) lowercase : Dict = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. lowercase : List[str] = [] for i in range(0, x.shape[2], lowerCAmelCase ): lowercase : Optional[Any] = [] for j in range(0, x.shape[3], lowerCAmelCase ): lowercase : Tuple = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] lowercase : List[Any] = self.encoder(lowerCAmelCase ) lowercase : Tuple = self.quant_conv(lowerCAmelCase ) row.append(lowerCAmelCase ) rows.append(lowerCAmelCase ) lowercase : int = [] for i, row in enumerate(lowerCAmelCase ): lowercase : Union[str, Any] = [] for j, tile in enumerate(lowerCAmelCase ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: lowercase : Optional[Any] = self.blend_v(rows[i - 1][j], lowerCAmelCase, lowerCAmelCase ) if j > 0: lowercase : Dict = self.blend_h(row[j - 1], lowerCAmelCase, lowerCAmelCase ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(lowerCAmelCase, dim=3 ) ) lowercase : List[str] = torch.cat(lowerCAmelCase, dim=2 ) lowercase : Union[str, Any] = DiagonalGaussianDistribution(lowerCAmelCase ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=lowerCAmelCase ) def lowercase ( self : Union[str, Any], lowerCAmelCase : torch.FloatTensor, lowerCAmelCase : bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: lowercase : Optional[Any] = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) lowercase : List[str] = int(self.tile_sample_min_size * self.tile_overlap_factor ) lowercase : int = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. lowercase : Optional[Any] = [] for i in range(0, z.shape[2], lowerCAmelCase ): lowercase : Union[str, Any] = [] for j in range(0, z.shape[3], lowerCAmelCase ): lowercase : Any = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] lowercase : Optional[Any] = self.post_quant_conv(lowerCAmelCase ) lowercase : Optional[int] = self.decoder(lowerCAmelCase ) row.append(lowerCAmelCase ) rows.append(lowerCAmelCase ) lowercase : Tuple = [] for i, row in enumerate(lowerCAmelCase ): lowercase : List[str] = [] for j, tile in enumerate(lowerCAmelCase ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: lowercase : Optional[int] = self.blend_v(rows[i - 1][j], lowerCAmelCase, lowerCAmelCase ) if j > 0: lowercase : Dict = self.blend_h(row[j - 1], lowerCAmelCase, lowerCAmelCase ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(lowerCAmelCase, dim=3 ) ) lowercase : Optional[int] = torch.cat(lowerCAmelCase, dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase ) def lowercase ( self : List[str], lowerCAmelCase : torch.FloatTensor, lowerCAmelCase : bool = False, lowerCAmelCase : bool = True, lowerCAmelCase : Optional[torch.Generator] = None, ) -> Union[DecoderOutput, torch.FloatTensor]: lowercase : Optional[int] = sample lowercase : Optional[int] = self.encode(lowerCAmelCase ).latent_dist if sample_posterior: lowercase : List[str] = posterior.sample(generator=lowerCAmelCase ) else: lowercase : List[Any] = posterior.mode() lowercase : List[Any] = self.decode(lowerCAmelCase ).sample if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase )
53
"""simple docstring""" _UpperCamelCase: Dict = 2_5_6 # Modulus to hash a string _UpperCamelCase: Union[str, Any] = 1_0_0_0_0_0_3 def lowercase__ ( _UpperCAmelCase , _UpperCAmelCase ) -> bool: '''simple docstring''' lowercase : Dict = len(_UpperCAmelCase ) lowercase : Union[str, Any] = len(_UpperCAmelCase ) if p_len > t_len: return False lowercase : Union[str, Any] = 0 lowercase : Dict = 0 lowercase : Any = 1 # Calculating the hash of pattern and substring of text for i in range(_UpperCAmelCase ): lowercase : Dict = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus lowercase : Tuple = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue lowercase : Tuple = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash lowercase : str = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def lowercase__ ( ) -> None: '''simple docstring''' lowercase : Any = 'abc1abc12' lowercase : int = 'alskfjaldsabc1abc1abc12k23adsfabcabc' lowercase : Optional[int] = 'alskfjaldsk23adsfabcabc' assert rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) and not rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) # Test 2) lowercase : str = 'ABABX' lowercase : Tuple = 'ABABZABABYABABX' assert rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) # Test 3) lowercase : int = 'AAAB' lowercase : Union[str, Any] = 'ABAAAAAB' assert rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) # Test 4) lowercase : Union[str, Any] = 'abcdabcy' lowercase : List[str] = 'abcxabcdabxabcdabcdabcy' assert rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) # Test 5) lowercase : Dict = 'Lü' lowercase : Dict = 'Lüsai' assert rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) lowercase : List[Any] = 'Lue' assert not rabin_karp(_UpperCAmelCase , _UpperCAmelCase ) print('Success.' ) if __name__ == "__main__": test_rabin_karp()
53
1
"""simple docstring""" from importlib import import_module from .logging import get_logger lowerCAmelCase__ = get_logger(__name__) class __snake_case : def __init__( self : int , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any]=None ): """simple docstring""" _lowerCamelCase : Tuple = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self , __lowerCAmelCase , getattr(__lowerCAmelCase , __lowerCAmelCase ) ) _lowerCamelCase : Any = module._original_module if isinstance(__lowerCAmelCase , _PatchedModuleObj ) else module class __snake_case : snake_case__ : Dict = [] def __init__( self : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=None ): """simple docstring""" _lowerCamelCase : Optional[Any] = obj _lowerCamelCase : int = target _lowerCamelCase : int = new _lowerCamelCase : Tuple = target.split('''.''' )[0] _lowerCamelCase : Optional[Any] = {} _lowerCamelCase : Optional[int] = attrs or [] def __enter__( self : Optional[Any] ): """simple docstring""" *_lowerCamelCase , _lowerCamelCase : Optional[int] = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__lowerCAmelCase ) ): try: _lowerCamelCase : Union[str, Any] = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): _lowerCamelCase : Dict = getattr(self.obj , __lowerCAmelCase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__lowerCAmelCase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): _lowerCamelCase : Dict = obj_attr # patch at top level setattr(self.obj , __lowerCAmelCase , _PatchedModuleObj(__lowerCAmelCase , attrs=self.attrs ) ) _lowerCamelCase : Tuple = getattr(self.obj , __lowerCAmelCase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__lowerCAmelCase , __lowerCAmelCase , _PatchedModuleObj(getattr(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) , attrs=self.attrs ) ) _lowerCamelCase : int = getattr(__lowerCAmelCase , __lowerCAmelCase ) # finally set the target attribute setattr(__lowerCAmelCase , __lowerCAmelCase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: _lowerCamelCase : Optional[int] = getattr(import_module('''.'''.join(__lowerCAmelCase ) ) , __lowerCAmelCase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __lowerCAmelCase ) is attr_value: _lowerCamelCase : str = getattr(self.obj , __lowerCAmelCase ) setattr(self.obj , __lowerCAmelCase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" _lowerCamelCase : List[str] = globals()['''__builtins__'''][target_attr] setattr(self.obj , __lowerCAmelCase , self.new ) else: raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self : Any , *__lowerCAmelCase : Dict ): """simple docstring""" for attr in list(self.original ): setattr(self.obj , __lowerCAmelCase , self.original.pop(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.__enter__() self._active_patches.append(self ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
72
def __lowercase ( __lowerCAmelCase : str , __lowerCAmelCase : str ): def get_matched_characters(__lowerCAmelCase : str , __lowerCAmelCase : str ) -> str: a__ = [] a__ = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): a__ = int(max(0 , i - limit ) ) a__ = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(__lowerCAmelCase ) a__ = F'{_stra[0:_stra.index(__lowerCAmelCase )]} {_stra[_stra.index(__lowerCAmelCase ) + 1:]}' return "".join(__lowerCAmelCase ) # matching characters a__ = get_matched_characters(__lowerCAmelCase , __lowerCAmelCase ) a__ = get_matched_characters(__lowerCAmelCase , __lowerCAmelCase ) a__ = len(__lowerCAmelCase ) # transposition a__ = ( len([(ca, ca) for ca, ca in zip(__lowerCAmelCase , __lowerCAmelCase ) if ca != ca] ) // 2 ) if not match_count: a__ = 0.0 else: a__ = ( 1 / 3 * ( match_count / len(__lowerCAmelCase ) + match_count / len(__lowerCAmelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters a__ = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('''hello''', '''world'''))
240
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'gpt_neox' def __init__( self : Union[str, Any] , snake_case : List[str]=5_0432 , snake_case : int=6144 , snake_case : List[Any]=44 , snake_case : str=64 , snake_case : Optional[int]=2_4576 , snake_case : List[Any]="gelu" , snake_case : Optional[Any]=0.25 , snake_case : Optional[int]=1_0000 , snake_case : Union[str, Any]=0.0 , snake_case : str=0.0 , snake_case : Tuple=0.1 , snake_case : int=2048 , snake_case : Dict=0.02 , snake_case : Optional[int]=1e-5 , snake_case : Any=True , snake_case : int=0 , snake_case : str=2 , snake_case : Tuple=False , snake_case : Union[str, Any]=True , snake_case : List[Any]=None , **snake_case : List[str] , ): '''simple docstring''' super().__init__(bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) A__ : int = vocab_size A__ : Any = max_position_embeddings A__ : int = hidden_size A__ : int = num_hidden_layers A__ : Tuple = num_attention_heads A__ : Any = intermediate_size A__ : List[Any] = hidden_act A__ : List[Any] = rotary_pct A__ : Dict = rotary_emb_base A__ : Tuple = attention_dropout A__ : Optional[Any] = hidden_dropout A__ : Tuple = classifier_dropout A__ : List[Any] = initializer_range A__ : Union[str, Any] = layer_norm_eps A__ : Union[str, Any] = use_cache A__ : int = tie_word_embeddings A__ : List[str] = use_parallel_residual A__ : Optional[Any] = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( """The hidden size is not divisble by the number of attention heads! Make sure to update them!""" ) def _UpperCamelCase ( self : str ): '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , snake_case ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ F'got {self.rope_scaling}' ) A__ : List[Any] = self.rope_scaling.get("""type""" , snake_case ) A__ : Union[str, Any] = self.rope_scaling.get("""factor""" , snake_case ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(snake_case , snake_case ) or rope_scaling_factor <= 1.0: raise ValueError(F'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
296
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[int] , snake_case : List[str]=None , **snake_case : Any ): '''simple docstring''' warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , snake_case , ) super().__init__(args=snake_case , **snake_case )
296
1
"""simple docstring""" import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml a__ : List[Any] = NewType('''DataClass''', Any) a__ : str = NewType('''DataClassType''', Any) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {str(lowerCAmelCase_ ): choice for choice in choices} return lambda lowerCAmelCase_ : str_to_choice.get(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (*, lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = dataclasses.MISSING , lowerCAmelCase_ = dataclasses.MISSING , lowerCAmelCase_ = None , **lowerCAmelCase_ , ): '''simple docstring''' if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls __SCREAMING_SNAKE_CASE = {} if aliases is not None: __SCREAMING_SNAKE_CASE = aliases if help is not None: __SCREAMING_SNAKE_CASE = help return dataclasses.field(metadata=lowerCAmelCase_ , default=lowerCAmelCase_ , default_factory=lowerCAmelCase_ , **lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Iterable[DataClassType] def __init__( self : Any , UpperCAmelCase__ : Union[DataClassType, Iterable[DataClassType]] , **UpperCAmelCase__ : Optional[Any] ) -> Optional[int]: # To make the default appear when using --help if "formatter_class" not in kwargs: __SCREAMING_SNAKE_CASE = ArgumentDefaultsHelpFormatter super().__init__(**UpperCAmelCase__ ) if dataclasses.is_dataclass(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [dataclass_types] __SCREAMING_SNAKE_CASE = list(UpperCAmelCase__ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(UpperCAmelCase__ ) @staticmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser , UpperCAmelCase__ : dataclasses.Field ) -> Tuple: __SCREAMING_SNAKE_CASE = F"""--{field.name}""" __SCREAMING_SNAKE_CASE = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , UpperCAmelCase__ ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) __SCREAMING_SNAKE_CASE = kwargs.pop("aliases" , [] ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [aliases] __SCREAMING_SNAKE_CASE = getattr(field.type , "__origin__" , field.type ) if origin_type is Union or (hasattr(UpperCAmelCase__ , "UnionType" ) and isinstance(UpperCAmelCase__ , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(UpperCAmelCase__ ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." F""" Problem encountered in field '{field.name}'.""" ) if type(UpperCAmelCase__ ) not in field.type.__args__: # filter `str` in Union __SCREAMING_SNAKE_CASE = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] __SCREAMING_SNAKE_CASE = getattr(field.type , "__origin__" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) __SCREAMING_SNAKE_CASE = ( field.type.__args__[0] if isinstance(UpperCAmelCase__ , field.type.__args__[1] ) else field.type.__args__[1] ) __SCREAMING_SNAKE_CASE = getattr(field.type , "__origin__" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) __SCREAMING_SNAKE_CASE = {} if origin_type is Literal or (isinstance(field.type , UpperCAmelCase__ ) and issubclass(field.type , UpperCAmelCase__ )): if origin_type is Literal: __SCREAMING_SNAKE_CASE = field.type.__args__ else: __SCREAMING_SNAKE_CASE = [x.value for x in field.type] __SCREAMING_SNAKE_CASE = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: __SCREAMING_SNAKE_CASE = field.default else: __SCREAMING_SNAKE_CASE = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument __SCREAMING_SNAKE_CASE = copy(UpperCAmelCase__ ) # Hack because type=bool in argparse does not behave as we want. __SCREAMING_SNAKE_CASE = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. __SCREAMING_SNAKE_CASE = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way __SCREAMING_SNAKE_CASE = default # This tells argparse we accept 0 or 1 value after --field_name __SCREAMING_SNAKE_CASE = "?" # This is the value that will get picked if we do --field_name (without value) __SCREAMING_SNAKE_CASE = True elif isclass(UpperCAmelCase__ ) and issubclass(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = field.type.__args__[0] __SCREAMING_SNAKE_CASE = "+" if field.default_factory is not dataclasses.MISSING: __SCREAMING_SNAKE_CASE = field.default_factory() elif field.default is dataclasses.MISSING: __SCREAMING_SNAKE_CASE = True else: __SCREAMING_SNAKE_CASE = field.type if field.default is not dataclasses.MISSING: __SCREAMING_SNAKE_CASE = field.default elif field.default_factory is not dataclasses.MISSING: __SCREAMING_SNAKE_CASE = field.default_factory() else: __SCREAMING_SNAKE_CASE = True parser.add_argument(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): __SCREAMING_SNAKE_CASE = False parser.add_argument(F"""--no_{field.name}""" , action="store_false" , dest=field.name , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : DataClassType ) -> Union[str, Any]: if hasattr(UpperCAmelCase__ , "_argument_group_name" ): __SCREAMING_SNAKE_CASE = self.add_argument_group(dtype._argument_group_name ) else: __SCREAMING_SNAKE_CASE = self try: __SCREAMING_SNAKE_CASE = get_type_hints(UpperCAmelCase__ ) except NameError: raise RuntimeError( F"""Type resolution failed for {dtype}. Try declaring the class in global scope or """ "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 1_0) and "unsupported operand type(s) for |" in str(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = ".".join(map(UpperCAmelCase__ , sys.version_info[:3] ) ) raise RuntimeError( F"""Type resolution failed for {dtype} on Python {python_version}. Try removing """ "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(UpperCAmelCase__ ): if not field.init: continue __SCREAMING_SNAKE_CASE = type_hints[field.name] self._parse_dataclass_field(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Optional[Any]=None , ) -> Tuple[DataClass, ...]: if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): __SCREAMING_SNAKE_CASE = [] if args_filename: args_files.append(Path(UpperCAmelCase__ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values __SCREAMING_SNAKE_CASE = ArgumentParser() args_file_parser.add_argument(UpperCAmelCase__ , type=UpperCAmelCase__ , action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = args_file_parser.parse_known_args(args=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vars(UpperCAmelCase__ ).get(args_file_flag.lstrip("-" ) , UpperCAmelCase__ ) if cmd_args_file_paths: args_files.extend([Path(UpperCAmelCase__ ) for p in cmd_args_file_paths] ) __SCREAMING_SNAKE_CASE = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last __SCREAMING_SNAKE_CASE = file_args + args if args is not None else file_args + sys.argv[1:] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.parse_known_args(args=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] for dtype in self.dataclass_types: __SCREAMING_SNAKE_CASE = {f.name for f in dataclasses.fields(UpperCAmelCase__ ) if f.init} __SCREAMING_SNAKE_CASE = {k: v for k, v in vars(UpperCAmelCase__ ).items() if k in keys} for k in keys: delattr(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = dtype(**UpperCAmelCase__ ) outputs.append(UpperCAmelCase__ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(UpperCAmelCase__ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(F"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" ) return (*outputs,) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Dict[str, Any] , UpperCAmelCase__ : bool = False ) -> Tuple[DataClass, ...]: __SCREAMING_SNAKE_CASE = set(args.keys() ) __SCREAMING_SNAKE_CASE = [] for dtype in self.dataclass_types: __SCREAMING_SNAKE_CASE = {f.name for f in dataclasses.fields(UpperCAmelCase__ ) if f.init} __SCREAMING_SNAKE_CASE = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) __SCREAMING_SNAKE_CASE = dtype(**UpperCAmelCase__ ) outputs.append(UpperCAmelCase__ ) if not allow_extra_keys and unused_keys: raise ValueError(F"""Some keys are not used by the HfArgumentParser: {sorted(UpperCAmelCase__ )}""" ) return tuple(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : bool = False ) -> Tuple[DataClass, ...]: with open(Path(UpperCAmelCase__ ) , encoding="utf-8" ) as open_json_file: __SCREAMING_SNAKE_CASE = json.loads(open_json_file.read() ) __SCREAMING_SNAKE_CASE = self.parse_dict(UpperCAmelCase__ , allow_extra_keys=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : bool = False ) -> Tuple[DataClass, ...]: __SCREAMING_SNAKE_CASE = self.parse_dict(yaml.safe_load(Path(UpperCAmelCase__ ).read_text() ) , allow_extra_keys=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
54
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class a ( a_ ): def __init__( self , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase ): lowercase = parent lowercase = config_class lowercase = has_text_modality lowercase = kwargs lowercase = common_properties def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) lowercase = ( ['hidden_size', 'num_attention_heads', 'num_hidden_layers'] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(['vocab_size'] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(_lowerCamelCase , _lowerCamelCase ) , msg=F'`{prop}` does not exist' ) # Test that config has the common properties as setter for idx, name in enumerate(_lowerCamelCase ): try: setattr(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.parent.assertEqual( getattr(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase , _lowerCamelCase )}' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(_lowerCamelCase ): try: lowercase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase , _lowerCamelCase )}' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) lowercase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , _lowerCamelCase ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase = os.path.join(_lowerCamelCase , 'config.json' ) config_first.to_json_file(_lowerCamelCase ) lowercase = self.config_class.from_json_file(_lowerCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(_lowerCamelCase ) lowercase = self.config_class.from_pretrained(_lowerCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) lowercase = 'test' with tempfile.TemporaryDirectory() as tmpdirname: lowercase = os.path.join(_lowerCamelCase , _lowerCamelCase ) config_first.save_pretrained(_lowerCamelCase ) lowercase = self.config_class.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) lowercase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def UpperCamelCase_ ( self ): if self.config_class.is_composition: return lowercase = self.config_class() self.parent.assertIsNotNone(_lowerCamelCase ) def UpperCamelCase_ ( self ): lowercase = copy.deepcopy(_lowerCamelCase ) lowercase = self.config_class(**_lowerCamelCase ) lowercase = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa) ) elif getattr(_lowerCamelCase , _lowerCamelCase ) != value: wrong_values.append((key, getattr(_lowerCamelCase , _lowerCamelCase ), value) ) if len(_lowerCamelCase ) > 0: lowercase = '\n'.join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values] ) raise ValueError(F'The following keys were not properly set in the config:\n{errors}' ) def UpperCamelCase_ ( self ): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
220
0
"""simple docstring""" from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowerCamelCase_ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): lowerCamelCase__ : List[str] = cva.getAffineTransform(_lowerCamelCase , _lowerCamelCase ) return cva.warpAffine(_lowerCamelCase , _lowerCamelCase , (rows, cols) ) if __name__ == "__main__": # read original image A_ : Union[str, Any] = cva.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value A_ : Dict = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A_ : Any = gray_img.shape # set different points to rotate image A_ : Union[str, Any] = np.array([[50, 50], [2_00, 50], [50, 2_00]], np.floataa) A_ : Optional[Any] = np.array([[10, 1_00], [2_00, 50], [1_00, 2_50]], np.floataa) A_ : List[Any] = np.array([[50, 50], [1_50, 50], [1_20, 2_00]], np.floataa) A_ : str = np.array([[10, 1_00], [80, 50], [1_80, 2_50]], np.floataa) # add all rotated images in a list A_ : str = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations A_ : Optional[Any] = plt.figure(1) A_ : Tuple = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
366
"""simple docstring""" import re def lowerCamelCase_ ( _lowerCamelCase ): if len(re.findall('[ATCG]' , _lowerCamelCase ) ) != len(_lowerCamelCase ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' , 'TAGC' ) ) if __name__ == "__main__": import doctest doctest.testmod()
316
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer a : Optional[int] = logging.get_logger(__name__) a : str = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} a : Optional[int] = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } a : Dict = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } a : List[str] = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class a ( lowercase__ ): """simple docstring""" a : Any = VOCAB_FILES_NAMES a : str = PRETRAINED_VOCAB_FILES_MAP a : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : Dict = PRETRAINED_INIT_CONFIGURATION a : Tuple = ['input_ids', 'attention_mask'] a : Optional[int] = DistilBertTokenizer def __init__( self : Any , __lowercase : List[Any]=None , __lowercase : List[Any]=None , __lowercase : List[Any]=True , __lowercase : Dict="[UNK]" , __lowercase : Optional[Any]="[SEP]" , __lowercase : int="[PAD]" , __lowercase : List[str]="[CLS]" , __lowercase : Any="[MASK]" , __lowercase : Union[str, Any]=True , __lowercase : str=None , **__lowercase : int , ) -> Union[str, Any]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) __UpperCAmelCase : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __lowercase ) != tokenize_chinese_chars ): __UpperCAmelCase : List[Any] = getattr(__lowercase , normalizer_state.pop("""type""" ) ) __UpperCAmelCase : Dict = do_lower_case __UpperCAmelCase : Tuple = strip_accents __UpperCAmelCase : Union[str, Any] = tokenize_chinese_chars __UpperCAmelCase : str = normalizer_class(**__lowercase ) __UpperCAmelCase : List[str] = do_lower_case def UpperCAmelCase ( self : Dict , __lowercase : int , __lowercase : int=None ) -> Any: __UpperCAmelCase : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase ( self : str , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: __UpperCAmelCase : int = [self.sep_token_id] __UpperCAmelCase : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase ( self : Dict , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: __UpperCAmelCase : Tuple = self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
114
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging a : Tuple = logging.get_logger(__name__) a : Optional[Any] = { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json", } class a ( lowercase__ ): """simple docstring""" a : str = 'mvp' a : Optional[Any] = ['past_key_values'] a : int = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Dict , __lowercase : Tuple=50267 , __lowercase : Optional[int]=1024 , __lowercase : Any=12 , __lowercase : List[Any]=4096 , __lowercase : Optional[Any]=16 , __lowercase : List[str]=12 , __lowercase : Optional[Any]=4096 , __lowercase : Tuple=16 , __lowercase : Union[str, Any]=0.0 , __lowercase : str=0.0 , __lowercase : Any="gelu" , __lowercase : Any=1024 , __lowercase : List[str]=0.1 , __lowercase : List[Any]=0.0 , __lowercase : int=0.0 , __lowercase : str=0.02 , __lowercase : Tuple=0.0 , __lowercase : Union[str, Any]=False , __lowercase : Dict=True , __lowercase : List[Any]=1 , __lowercase : Optional[Any]=0 , __lowercase : Union[str, Any]=2 , __lowercase : Optional[int]=True , __lowercase : Dict=2 , __lowercase : int=2 , __lowercase : Union[str, Any]=False , __lowercase : Union[str, Any]=100 , __lowercase : str=800 , **__lowercase : Union[str, Any] , ) -> Any: __UpperCAmelCase : List[str] = vocab_size __UpperCAmelCase : Union[str, Any] = max_position_embeddings __UpperCAmelCase : Optional[Any] = d_model __UpperCAmelCase : int = encoder_ffn_dim __UpperCAmelCase : Tuple = encoder_layers __UpperCAmelCase : List[str] = encoder_attention_heads __UpperCAmelCase : Any = decoder_ffn_dim __UpperCAmelCase : List[Any] = decoder_layers __UpperCAmelCase : str = decoder_attention_heads __UpperCAmelCase : Optional[int] = dropout __UpperCAmelCase : Tuple = attention_dropout __UpperCAmelCase : int = activation_dropout __UpperCAmelCase : List[Any] = activation_function __UpperCAmelCase : Tuple = init_std __UpperCAmelCase : Any = encoder_layerdrop __UpperCAmelCase : Union[str, Any] = decoder_layerdrop __UpperCAmelCase : List[Any] = classifier_dropout __UpperCAmelCase : Optional[int] = use_cache __UpperCAmelCase : int = encoder_layers __UpperCAmelCase : Union[str, Any] = scale_embedding # scale factor will be sqrt(d_model) if True __UpperCAmelCase : Tuple = use_prompt __UpperCAmelCase : str = prompt_length __UpperCAmelCase : Union[str, Any] = prompt_mid_dim super().__init__( pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , is_encoder_decoder=__lowercase , decoder_start_token_id=__lowercase , forced_eos_token_id=__lowercase , **__lowercase , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , __lowercase ): __UpperCAmelCase : Optional[Any] = self.bos_token_id warnings.warn( f"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """ """The config can simply be saved and uploaded again to be fixed.""" )
114
1
import numpy as np def SCREAMING_SNAKE_CASE__ ( lowercase ) -> np.ndarray: return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE__ ( lowercase ) -> np.ndarray: return vector * sigmoid(lowercase ) if __name__ == "__main__": import doctest doctest.testmod()
176
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ) -> Union[str, Any]: if isinstance(lowercase ,torch.Tensor ): return image elif isinstance(lowercase ,PIL.Image.Image ): snake_case : str = [image] if isinstance(image[0] ,PIL.Image.Image ): snake_case : List[Any] = [np.array(i.resize((w, h) ,resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] snake_case : Optional[int] = np.concatenate(lowercase ,axis=0 ) snake_case : str = np.array(lowercase ).astype(np.floataa ) / 255.0 snake_case : List[str] = image.transpose(0 ,3 ,1 ,2 ) snake_case : Any = 2.0 * image - 1.0 snake_case : Optional[Any] = torch.from_numpy(lowercase ) elif isinstance(image[0] ,torch.Tensor ): snake_case : Optional[int] = torch.cat(lowercase ,dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase=0.9995 ) -> Optional[int]: if not isinstance(lowercase ,np.ndarray ): snake_case : Any = True snake_case : str = va.device snake_case : Optional[Any] = va.cpu().numpy() snake_case : str = va.cpu().numpy() snake_case : Tuple = np.sum(va * va / (np.linalg.norm(lowercase ) * np.linalg.norm(lowercase )) ) if np.abs(lowercase ) > DOT_THRESHOLD: snake_case : Optional[int] = (1 - t) * va + t * va else: snake_case : List[Any] = np.arccos(lowercase ) snake_case : str = np.sin(lowercase ) snake_case : int = theta_a * t snake_case : Dict = np.sin(lowercase ) snake_case : Optional[Any] = np.sin(theta_a - theta_t ) / sin_theta_a snake_case : Union[str, Any] = sin_theta_t / sin_theta_a snake_case : Union[str, Any] = sa * va + sa * va if inputs_are_torch: snake_case : List[Any] = torch.from_numpy(lowercase ).to(lowercase ) return va def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> Tuple: snake_case : Dict = F.normalize(lowercase ,dim=-1 ) snake_case : Optional[Any] = F.normalize(lowercase ,dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> str: for param in model.parameters(): snake_case : Tuple = value class __lowercase (UpperCamelCase__ ): """simple docstring""" def __init__( self , A , A , A , A , A , A , A , A=None , A=None , A=None , ) -> List[Any]: super().__init__() self.register_modules( vae=A , text_encoder=A , clip_model=A , tokenizer=A , unet=A , scheduler=A , feature_extractor=A , coca_model=A , coca_tokenizer=A , coca_transform=A , ) snake_case : Optional[int] = ( feature_extractor.size if isinstance(feature_extractor.size , A ) else feature_extractor.size["""shortest_edge"""] ) snake_case : Union[str, Any] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , A ) set_requires_grad(self.clip_model , A ) def UpperCAmelCase ( self , A = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory snake_case : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A ) def UpperCAmelCase ( self ) -> Optional[int]: self.enable_attention_slicing(A ) def UpperCAmelCase ( self ) -> Any: set_requires_grad(self.vae , A ) def UpperCAmelCase ( self ) -> List[Any]: set_requires_grad(self.vae , A ) def UpperCAmelCase ( self ) -> Union[str, Any]: set_requires_grad(self.unet , A ) def UpperCAmelCase ( self ) -> Tuple: set_requires_grad(self.unet , A ) def UpperCAmelCase ( self , A , A , A ) -> Dict: # get the original timestep using init_timestep snake_case : Tuple = min(int(num_inference_steps * strength ) , A ) snake_case : List[str] = max(num_inference_steps - init_timestep , 0 ) snake_case : List[str] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , A , A , A , A , A , A=None ) -> List[str]: if not isinstance(A , torch.Tensor ): raise ValueError(f"""`image` has to be of type `torch.Tensor` but is {type(A )}""" ) snake_case : str = image.to(device=A , dtype=A ) if isinstance(A , A ): snake_case : int = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(A ) ] snake_case : str = torch.cat(A , dim=0 ) else: snake_case : List[Any] = self.vae.encode(A ).latent_dist.sample(A ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case : Dict = 0.1_82_15 * init_latents snake_case : Tuple = init_latents.repeat_interleave(A , dim=0 ) snake_case : Optional[int] = randn_tensor(init_latents.shape , generator=A , device=A , dtype=A ) # get latents snake_case : Union[str, Any] = self.scheduler.add_noise(A , A , A ) snake_case : List[Any] = init_latents return latents def UpperCAmelCase ( self , A ) -> int: snake_case : Optional[Any] = self.coca_transform(A ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): snake_case : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) snake_case : int = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("""<end_of_text>""" )[0].replace("""<start_of_text>""" , """""" ).rstrip(""" .,""" ) def UpperCAmelCase ( self , A , A ) -> List[Any]: snake_case : Tuple = self.feature_extractor.preprocess(A ) snake_case : List[Any] = torch.from_numpy(clip_image_input["""pixel_values"""][0] ).unsqueeze(0 ).to(self.device ).half() snake_case : Optional[int] = self.clip_model.get_image_features(A ) snake_case : List[str] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=A ) snake_case : Tuple = image_embeddings_clip.repeat_interleave(A , dim=0 ) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , A , A , A , A , A , A , A , ) -> Any: snake_case : Dict = latents.detach().requires_grad_() snake_case : str = self.scheduler.scale_model_input(A , A ) # predict the noise residual snake_case : str = self.unet(A , A , encoder_hidden_states=A ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): snake_case : int = self.scheduler.alphas_cumprod[timestep] snake_case : Tuple = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case : Any = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 snake_case : str = torch.sqrt(A ) snake_case : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , A ): snake_case : int = self.scheduler.sigmas[index] snake_case : List[Any] = latents - sigma * noise_pred else: raise ValueError(f"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case : List[str] = 1 / 0.1_82_15 * sample snake_case : str = self.vae.decode(A ).sample snake_case : Any = (image / 2 + 0.5).clamp(0 , 1 ) snake_case : str = transforms.Resize(self.feature_extractor_size )(A ) snake_case : Dict = self.normalize(A ).to(latents.dtype ) snake_case : Union[str, Any] = self.clip_model.get_image_features(A ) snake_case : List[str] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=A ) snake_case : Optional[int] = spherical_dist_loss(A , A ).mean() * clip_guidance_scale snake_case : int = -torch.autograd.grad(A , A )[0] if isinstance(self.scheduler , A ): snake_case : Union[str, Any] = latents.detach() + grads * (sigma**2) snake_case : Union[str, Any] = noise_pred_original else: snake_case : List[str] = noise_pred_original - torch.sqrt(A ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , A , A , A = None , A = None , A = 5_1_2 , A = 5_1_2 , A = 0.6 , A = 5_0 , A = 7.5 , A = 1 , A = 0.0 , A = 1_0_0 , A = None , A = "pil" , A = True , A = 0.8 , A = 0.1 , A = 0.1 , ) -> Union[str, Any]: if isinstance(A , A ) and len(A ) != batch_size: raise ValueError(f"""You have passed {batch_size} batch_size, but only {len(A )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(A , torch.Generator ) and batch_size > 1: snake_case : Dict = [generator] + [None] * (batch_size - 1) snake_case : Tuple = [ ("""model""", self.coca_model is None), ("""tokenizer""", self.coca_tokenizer is None), ("""transform""", self.coca_transform is None), ] snake_case : List[str] = [x[0] for x in coca_is_none if x[1]] snake_case : Optional[int] = """, """.join(A ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(A ): raise ValueError( f"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" f"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) snake_case : Tuple = self.get_image_description(A ) if style_prompt is None: if len(A ): raise ValueError( f"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" f""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) snake_case : List[Any] = self.get_image_description(A ) # get prompt text embeddings for content and style snake_case : Dict = self.tokenizer( A , padding="""max_length""" , max_length=self.tokenizer.model_max_length , truncation=A , return_tensors="""pt""" , ) snake_case : str = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] snake_case : Dict = self.tokenizer( A , padding="""max_length""" , max_length=self.tokenizer.model_max_length , truncation=A , return_tensors="""pt""" , ) snake_case : Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] snake_case : List[str] = slerp(A , A , A ) # duplicate text embeddings for each generation per prompt snake_case : List[Any] = text_embeddings.repeat_interleave(A , dim=0 ) # set timesteps snake_case : Union[str, Any] = """offset""" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) snake_case : Optional[Any] = {} if accepts_offset: snake_case : Dict = 1 self.scheduler.set_timesteps(A , **A ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) snake_case , snake_case : List[Any] = self.get_timesteps(A , A , self.device ) snake_case : List[str] = timesteps[:1].repeat(A ) # Preprocess image snake_case : Dict = preprocess(A , A , A ) snake_case : List[Any] = self.prepare_latents( A , A , A , text_embeddings.dtype , self.device , A ) snake_case : Optional[int] = preprocess(A , A , A ) snake_case : Optional[Any] = self.prepare_latents( A , A , A , text_embeddings.dtype , self.device , A ) snake_case : str = slerp(A , A , A ) if clip_guidance_scale > 0: snake_case : List[Any] = self.get_clip_image_embeddings(A , A ) snake_case : Any = self.get_clip_image_embeddings(A , A ) snake_case : Tuple = slerp( A , A , A ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. snake_case : Optional[Any] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: snake_case : List[str] = content_text_input.input_ids.shape[-1] snake_case : Any = self.tokenizer([""""""] , padding="""max_length""" , max_length=A , return_tensors="""pt""" ) snake_case : Tuple = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt snake_case : Tuple = uncond_embeddings.repeat_interleave(A , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes snake_case : str = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. snake_case : Tuple = (batch_size, self.unet.config.in_channels, height // 8, width // 8) snake_case : List[Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps snake_case : List[Any] = torch.randn(A , generator=A , device="""cpu""" , dtype=A ).to( self.device ) else: snake_case : Optional[int] = torch.randn(A , generator=A , device=self.device , dtype=A ) else: if latents.shape != latents_shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) snake_case : Union[str, Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case : Tuple = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Dict = {} if accepts_eta: snake_case : Union[str, Any] = eta # check if the scheduler accepts generator snake_case : List[Any] = """generator""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: snake_case : List[str] = generator with self.progress_bar(total=A ): for i, t in enumerate(A ): # expand the latents if we are doing classifier free guidance snake_case : Optional[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : List[str] = self.scheduler.scale_model_input(A , A ) # predict the noise residual snake_case : Any = self.unet(A , A , encoder_hidden_states=A ).sample # perform classifier free guidance if do_classifier_free_guidance: snake_case , snake_case : int = noise_pred.chunk(2 ) snake_case : Tuple = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: snake_case : Any = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) snake_case , snake_case : List[Any] = self.cond_fn( A , A , A , A , A , A , A , ) # compute the previous noisy sample x_t -> x_t-1 snake_case : Tuple = self.scheduler.step(A , A , A , **A ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case : str = 1 / 0.1_82_15 * latents snake_case : Optional[Any] = self.vae.decode(A ).sample snake_case : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) snake_case : str = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Tuple = self.numpy_to_pil(A ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=A , nsfw_content_detected=A )
176
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str = logging.get_logger(__name__) _A : int = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class a__ ( a_ ): __lowerCAmelCase = """rwkv""" __lowerCAmelCase = {"""max_position_embeddings""": """context_length"""} def __init__( self , _a=50_277 , _a=1_024 , _a=4_096 , _a=32 , _a=None , _a=None , _a=1E-5 , _a=0 , _a=0 , _a=6 , _a=False , _a=True , **_a , ): lowercase : Any = vocab_size lowercase : int = context_length lowercase : List[Any] = hidden_size lowercase : Optional[Any] = num_hidden_layers lowercase : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size lowercase : str = intermediate_size if intermediate_size is not None else 4 * hidden_size lowercase : Optional[Any] = layer_norm_epsilon lowercase : Tuple = rescale_every lowercase : Optional[int] = use_cache lowercase : Tuple = bos_token_id lowercase : Tuple = eos_token_id super().__init__( tie_word_embeddings=_a , bos_token_id=_a , eos_token_id=_a , **_a )
202
"""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_fnet import FNetTokenizer else: _A : Union[str, Any] = None _A : str = logging.get_logger(__name__) _A : Tuple = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} _A : Optional[Any] = { """vocab_file""": { """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/spiece.model""", """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/spiece.model""", }, """tokenizer_file""": { """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json""", """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json""", }, } _A : Optional[Any] = { """google/fnet-base""": 5_12, """google/fnet-large""": 5_12, } _A : List[str] = """▁""" class a__ ( a_ ): __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["""input_ids""", """token_type_ids"""] __lowerCAmelCase = FNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=True , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , **_a , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. lowercase : int = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , **_a , ) lowercase : Dict = do_lower_case lowercase : Union[str, Any] = remove_space lowercase : Any = keep_accents lowercase : List[Any] = vocab_file lowercase : Union[str, Any] = False if not self.vocab_file else True def __magic_name__ ( self , _a , _a = None ): lowercase : Optional[Any] = [self.sep_token_id] lowercase : str = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __magic_name__ ( self , _a , _a = None ): lowercase : Any = [self.sep_token_id] lowercase : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase : Optional[Any] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
202
1
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class __UpperCAmelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ) -> str: return datasets.DatasetInfo( features=datasets.Features({'''content''': datasets.Value('''string''' )} ) , supervised_keys=_SCREAMING_SNAKE_CASE , ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_dummy_examples()} )] def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(_SCREAMING_SNAKE_CASE ) class __UpperCAmelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def __A ( self ) -> Optional[Any]: return datasets.DatasetInfo( features=datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) , supervised_keys=_SCREAMING_SNAKE_CASE , ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_nested_examples()} ) ] def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(_SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( ) -> List[Any]: return [(i, {"content": content}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] def _UpperCAmelCase ( ) -> Optional[int]: return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )] class __UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @require_beam def __A ( self ) -> int: A_ = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A_ = DummyBeamDataset(cache_dir=_SCREAMING_SNAKE_CASE , beam_runner='''DirectRunner''' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(_SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , F'''{builder.name}-train.arrow''' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) ) A_ = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , _SCREAMING_SNAKE_CASE ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , _SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset['''train'''][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset @require_beam def __A ( self ) -> List[Any]: import apache_beam as beam A_ = beam.io.parquetio.WriteToParquet A_ = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A_ = DummyBeamDataset(cache_dir=_SCREAMING_SNAKE_CASE , beam_runner='''DirectRunner''' ) with patch('''apache_beam.io.parquetio.WriteToParquet''' ) as write_parquet_mock: A_ = partial(_SCREAMING_SNAKE_CASE , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( _SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , F'''{builder.name}-train-00000-of-00002.arrow''' ) ) ) self.assertTrue( os.path.exists( os.path.join( _SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , F'''{builder.name}-train-00000-of-00002.arrow''' ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) ) A_ = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , _SCREAMING_SNAKE_CASE ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , _SCREAMING_SNAKE_CASE ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset['''train''']['''content'''] ) , sorted(['''foo''', '''bar''', '''foobar'''] ) ) self.assertTrue( os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset @require_beam def __A ( self ) -> int: with tempfile.TemporaryDirectory() as tmp_cache_dir: A_ = DummyBeamDataset(cache_dir=_SCREAMING_SNAKE_CASE ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __A ( self ) -> Dict: A_ = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: A_ = NestedBeamDataset(cache_dir=_SCREAMING_SNAKE_CASE , beam_runner='''DirectRunner''' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(_SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , F'''{builder.name}-train.arrow''' ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) ) A_ = builder.as_dataset() self.assertEqual(dset['''train'''].num_rows , _SCREAMING_SNAKE_CASE ) self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , _SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset['''train'''][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset['''train'''][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) ) del dset
358
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def _UpperCAmelCase ( _UpperCamelCase : Union[str, Any]=None ) -> List[Any]: if subparsers is not None: A_ = subparsers.add_parser('''env''' ) else: A_ = argparse.ArgumentParser('''Accelerate env command''' ) parser.add_argument( '''--config_file''', default=_UpperCamelCase, help='''The config file to use for the default values in the launching script.''' ) if subparsers is not None: parser.set_defaults(func=_UpperCamelCase ) return parser def _UpperCAmelCase ( _UpperCamelCase : Dict ) -> Dict: A_ = torch.__version__ A_ = torch.cuda.is_available() A_ = is_xpu_available() A_ = is_npu_available() A_ = '''Not found''' # Get the default from the config file. if args.config_file is not None or os.path.isfile(_UpperCamelCase ): A_ = load_config_from_file(args.config_file ).to_dict() A_ = { '''`Accelerate` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Numpy version''': np.__version__, '''PyTorch version (GPU?)''': F'''{pt_version} ({pt_cuda_available})''', '''PyTorch XPU available''': str(_UpperCamelCase ), '''PyTorch NPU available''': str(_UpperCamelCase ), '''System RAM''': F'''{psutil.virtual_memory().total / 10_24 ** 3:.2f} GB''', } if pt_cuda_available: A_ = torch.cuda.get_device_name() print('''\nCopy-and-paste the text below in your GitHub issue\n''' ) print('''\n'''.join([F'''- {prop}: {val}''' for prop, val in info.items()] ) ) print('''- `Accelerate` default config:''' if args.config_file is None else '''- `Accelerate` config passed:''' ) A_ = ( '''\n'''.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(_UpperCamelCase, _UpperCamelCase ) else F'''\t{accelerate_config}''' ) print(_UpperCamelCase ) A_ = accelerate_config return info def _UpperCAmelCase ( ) -> int: A_ = env_command_parser() A_ = parser.parse_args() env_command(_UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
18
0
"""simple docstring""" from collections.abc import Sequence def __lowerCamelCase ( a_ : Any , a_ : Tuple ) -> float: return sum(c * (x**i) for i, c in enumerate(a_ ) ) def __lowerCamelCase ( a_ : Any , a_ : Tuple ) -> float: __SCREAMING_SNAKE_CASE :str = 0.0 for coeff in reversed(a_ ): __SCREAMING_SNAKE_CASE :Any = result * x + coeff return result if __name__ == "__main__": lowerCamelCase_ = (0.0, 0.0, 5.0, 9.3, 7.0) lowerCamelCase_ = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
191
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() A_ :List[str] = [ '''word_embeddings_layernorm.weight''', '''word_embeddings_layernorm.bias''', '''input_layernorm.weight''', '''input_layernorm.bias''', '''post_attention_layernorm.weight''', '''post_attention_layernorm.bias''', '''self_attention.dense.bias''', '''mlp.dense_4h_to_h.bias''', '''ln_f.weight''', '''ln_f.bias''', ] A_ :Optional[Any] = [ '''mlp.dense_4h_to_h.weight''', '''self_attention.dense.weight''', ] def A ( a_ ,a_ ) -> str: __UpperCamelCase : Any ={ 'word_embeddings.weight': 'word_embeddings.weight', 'word_embeddings.norm.weight': 'word_embeddings_layernorm.weight', 'word_embeddings.norm.bias': 'word_embeddings_layernorm.bias', 'weight': 'ln_f.weight', 'bias': 'ln_f.bias', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks __UpperCamelCase : Tuple =int(re.match(r'.*layer_(\d*).*' ,a_ )[1] ) layer_number -= 3 return F'h.{layer_number}.' + key def A ( a_ ) -> Any: if dtype == torch.bool: return 1 / 8 __UpperCamelCase : Dict =re.search(r'[^\d](\d+)$' ,str(a_ ) ) if bit_search is None: raise ValueError(F'`dtype` is not a valid dtype: {dtype}.' ) __UpperCamelCase : Tuple =int(bit_search.groups()[0] ) return bit_size // 8 def A ( a_ ,a_ ,a_ ,a_ ,a_ ) -> Dict: # Construct model if bloom_config_file == "": __UpperCamelCase : List[Any] =BloomConfig() else: __UpperCamelCase : List[str] =BloomConfig.from_json_file(a_ ) if shard_model: __UpperCamelCase : int =os.listdir(a_ ) __UpperCamelCase : Union[str, Any] =sorted(filter(lambda a_ : s.startswith('layer' ) and "model_00" in s ,a_ ) ) __UpperCamelCase : Optional[Any] ={'weight_map': {}, 'metadata': {}} __UpperCamelCase : Dict =0 __UpperCamelCase : int =None __UpperCamelCase : Any =BloomConfig() for j, file in enumerate(a_ ): print('Processing file: {}'.format(a_ ) ) __UpperCamelCase : Optional[int] =None for i in range(a_ ): # load all TP files __UpperCamelCase : Dict =file.replace('model_00' ,F'model_0{i}' ) __UpperCamelCase : Optional[Any] =torch.load(os.path.join(a_ ,a_ ) ,map_location='cpu' ) # Rename keys in the transformers names __UpperCamelCase : int =list(temp.keys() ) for key in keys: __UpperCamelCase : Dict =temp.pop(a_ ) if tensors is None: __UpperCamelCase : Any =temp else: for key in tensors.keys(): if any(key.endswith(a_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel __UpperCamelCase : List[Any] =1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks __UpperCamelCase : Any =torch.cat([tensors[key], temp[key]] ,dim=a_ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(a_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): __UpperCamelCase : Optional[Any] =tensors[key] / pretraining_tp torch.save( a_ ,os.path.join( a_ ,'pytorch_model_{}-of-{}.bin'.format(str(j + 1 ).zfill(5 ) ,str(len(a_ ) ).zfill(5 ) ) ,) ,) for key in tensors.keys(): __UpperCamelCase : Union[str, Any] =tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: __UpperCamelCase : int ='pytorch_model_{}-of-{}.bin'.format( str(j + 1 ).zfill(5 ) ,str(len(a_ ) ).zfill(5 ) ) __UpperCamelCase : Union[str, Any] =BloomConfig() __UpperCamelCase : Tuple =pytorch_dump_folder_path + '/' + CONFIG_NAME __UpperCamelCase : Optional[int] =total_size with open(a_ ,'w' ,encoding='utf-8' ) as f: f.write(config.to_json_string() ) with open(os.path.join(a_ ,WEIGHTS_NAME + '.index.json' ) ,'w' ,encoding='utf-8' ) as f: __UpperCamelCase : List[Any] =json.dumps(a_ ,indent=2 ,sort_keys=a_ ) + '\n' f.write(a_ ) else: __UpperCamelCase : List[Any] =BloomModel(a_ ) __UpperCamelCase : Optional[Any] =os.listdir(a_ ) __UpperCamelCase : Dict =sorted(filter(lambda a_ : s.startswith('layer' ) and "model_00" in s ,a_ ) ) __UpperCamelCase : Any =None for i, file in enumerate(a_ ): __UpperCamelCase : Union[str, Any] =None for i in range(a_ ): # load all TP files __UpperCamelCase : Optional[Any] =file.replace('model_00' ,F'model_0{i}' ) __UpperCamelCase : str =torch.load(os.path.join(a_ ,a_ ) ,map_location='cpu' ) # Rename keys in the transformers names __UpperCamelCase : List[str] =list(temp.keys() ) for key in keys: __UpperCamelCase : Union[str, Any] =temp.pop(a_ ) if tensors is None: __UpperCamelCase : Optional[Any] =temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(a_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel __UpperCamelCase : Optional[int] =1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks __UpperCamelCase : int =torch.cat([tensors[key], temp[key]] ,dim=a_ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(a_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): __UpperCamelCase : Dict =tensors[key] / pretraining_tp __UpperCamelCase : str =model.load_state_dict(a_ ,strict=a_ ) assert not other_keys.unexpected_keys, F'The keys {other_keys.unexpected_keys} are unexpected' if missing_keys is None: __UpperCamelCase : str =set(other_keys.missing_keys ) else: __UpperCamelCase : int =missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, F'The keys {missing_keys} are missing' # Save pytorch-model os.makedirs(a_ ,exist_ok=a_ ) __UpperCamelCase : Optional[int] =pytorch_dump_folder_path + '/' + WEIGHTS_NAME __UpperCamelCase : Dict =pytorch_dump_folder_path + '/' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}' ) if config.torch_dtype is not None: __UpperCamelCase : List[str] =model.to(config.torch_dtype ) torch.save(model.state_dict() ,a_ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(a_ ,'w' ,encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ :Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bloom_checkpoint_path''', default=None, type=str, required=True, help='''Path to the Megatron-LM checkpoint path.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--bloom_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--shard_model''', action='''store_true''', help='''An optional setting to shard the output model \nThis enables sharding the converted checkpoint''', ) parser.add_argument( '''--pretraining_tp''', default=4, type=int, help='''Pretraining TP rank that has been used when training the model in Megatron-LM \n''', ) A_ :str = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
71
0
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _UpperCAmelCase( unittest.TestCase ): lowercase__ = MODEL_FOR_MASKED_LM_MAPPING lowercase__ = TF_MODEL_FOR_MASKED_LM_MAPPING def UpperCAmelCase ( self) -> Any: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , top_k=2 , framework='''tf''') _UpperCamelCase = unmasker('''My name is <mask>''') self.assertEqual( nested_simplify(__a , decimals=6) , [ {'''sequence''': '''My name is grouped''', '''score''': 2.1e-05, '''token''': 3_80_15, '''token_str''': ''' grouped'''}, {'''sequence''': '''My name is accuser''', '''score''': 2.1e-05, '''token''': 2_55_06, '''token_str''': ''' accuser'''}, ] , ) _UpperCamelCase = unmasker('''The largest city in France is <mask>''') self.assertEqual( nested_simplify(__a , decimals=6) , [ { '''sequence''': '''The largest city in France is grouped''', '''score''': 2.1e-05, '''token''': 3_80_15, '''token_str''': ''' grouped''', }, { '''sequence''': '''The largest city in France is accuser''', '''score''': 2.1e-05, '''token''': 2_55_06, '''token_str''': ''' accuser''', }, ] , ) _UpperCamelCase = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3) self.assertEqual( nested_simplify(__a , decimals=6) , [ {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 1_36_06, '''token_str''': ''' Clara'''}, {'''sequence''': '''My name is Patrick''', '''score''': 2e-05, '''token''': 34_99, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Te''', '''score''': 1.9e-05, '''token''': 29_41, '''token_str''': ''' Te'''}, ] , ) @require_torch def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , top_k=2 , framework='''pt''') _UpperCamelCase = unmasker('''My name is <mask>''') self.assertEqual( nested_simplify(__a , decimals=6) , [ {'''sequence''': '''My name is Maul''', '''score''': 2.2e-05, '''token''': 3_56_76, '''token_str''': ''' Maul'''}, {'''sequence''': '''My name isELS''', '''score''': 2.2e-05, '''token''': 1_64_16, '''token_str''': '''ELS'''}, ] , ) _UpperCamelCase = unmasker('''The largest city in France is <mask>''') self.assertEqual( nested_simplify(__a , decimals=6) , [ { '''sequence''': '''The largest city in France is Maul''', '''score''': 2.2e-05, '''token''': 3_56_76, '''token_str''': ''' Maul''', }, {'''sequence''': '''The largest city in France isELS''', '''score''': 2.2e-05, '''token''': 1_64_16, '''token_str''': '''ELS'''}, ] , ) _UpperCamelCase = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3) self.assertEqual( nested_simplify(__a , decimals=6) , [ {'''sequence''': '''My name is Patrick''', '''score''': 2.1e-05, '''token''': 34_99, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Te''', '''score''': 2e-05, '''token''': 29_41, '''token_str''': ''' Te'''}, {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 1_36_06, '''token_str''': ''' Clara'''}, ] , ) _UpperCamelCase = unmasker('''My name is <mask> <mask>''' , top_k=2) self.assertEqual( nested_simplify(__a , decimals=6) , [ [ { '''score''': 2.2e-05, '''token''': 3_56_76, '''token_str''': ''' Maul''', '''sequence''': '''<s>My name is Maul<mask></s>''', }, {'''score''': 2.2e-05, '''token''': 1_64_16, '''token_str''': '''ELS''', '''sequence''': '''<s>My name isELS<mask></s>'''}, ], [ { '''score''': 2.2e-05, '''token''': 3_56_76, '''token_str''': ''' Maul''', '''sequence''': '''<s>My name is<mask> Maul</s>''', }, {'''score''': 2.2e-05, '''token''': 1_64_16, '''token_str''': '''ELS''', '''sequence''': '''<s>My name is<mask>ELS</s>'''}, ], ] , ) @require_torch_gpu def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = pipeline('''fill-mask''' , model='''hf-internal-testing/tiny-random-distilbert''' , device=0 , framework='''pt''') # convert model to fp16 pipe.model.half() _UpperCamelCase = pipe('''Paris is the [MASK] of France.''') # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(__a , __a) @slow @require_torch def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = pipeline(task='''fill-mask''' , model='''distilroberta-base''' , top_k=2 , framework='''pt''') self.run_large_test(__a) @slow @require_tf def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = pipeline(task='''fill-mask''' , model='''distilroberta-base''' , top_k=2 , framework='''tf''') self.run_large_test(__a) def UpperCAmelCase ( self , __a) -> Optional[int]: '''simple docstring''' _UpperCamelCase = unmasker('''My name is <mask>''') self.assertEqual( nested_simplify(__a) , [ {'''sequence''': '''My name is John''', '''score''': 0.008, '''token''': 6_10, '''token_str''': ''' John'''}, {'''sequence''': '''My name is Chris''', '''score''': 0.007, '''token''': 15_73, '''token_str''': ''' Chris'''}, ] , ) _UpperCamelCase = unmasker('''The largest city in France is <mask>''') self.assertEqual( nested_simplify(__a) , [ { '''sequence''': '''The largest city in France is Paris''', '''score''': 0.251, '''token''': 22_01, '''token_str''': ''' Paris''', }, { '''sequence''': '''The largest city in France is Lyon''', '''score''': 0.214, '''token''': 1_27_90, '''token_str''': ''' Lyon''', }, ] , ) _UpperCamelCase = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3) self.assertEqual( nested_simplify(__a) , [ {'''sequence''': '''My name is Patrick''', '''score''': 0.005, '''token''': 34_99, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Clara''', '''score''': 0.000, '''token''': 1_36_06, '''token_str''': ''' Clara'''}, {'''sequence''': '''My name is Te''', '''score''': 0.000, '''token''': 29_41, '''token_str''': ''' Te'''}, ] , ) @require_torch def UpperCAmelCase ( self) -> str: '''simple docstring''' _UpperCamelCase = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , framework='''pt''') _UpperCamelCase = None _UpperCamelCase = None self.run_pipeline_test(__a , []) @require_tf def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , framework='''tf''') _UpperCamelCase = None _UpperCamelCase = None self.run_pipeline_test(__a , []) def UpperCAmelCase ( self , __a , __a , __a) -> Tuple: '''simple docstring''' if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest('''The provided tokenizer has no mask token, (probably reformer or wav2vec2)''') _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a) _UpperCamelCase = [ F'''This is another {tokenizer.mask_token} test''', ] return fill_masker, examples def UpperCAmelCase ( self , __a , __a) -> str: '''simple docstring''' _UpperCamelCase = fill_masker.tokenizer _UpperCamelCase = fill_masker.model _UpperCamelCase = fill_masker( F'''This is a {tokenizer.mask_token}''' , ) self.assertEqual( __a , [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ] , ) _UpperCamelCase = fill_masker([F'''This is a {tokenizer.mask_token}''']) self.assertEqual( __a , [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ] , ) _UpperCamelCase = fill_masker([F'''This is a {tokenizer.mask_token}''', F'''Another {tokenizer.mask_token} great test.''']) self.assertEqual( __a , [ [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ], [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ], ] , ) with self.assertRaises(__a): fill_masker([None]) # No mask_token is not supported with self.assertRaises(__a): fill_masker('''This is''') self.run_test_top_k(__a , __a) self.run_test_targets(__a , __a) self.run_test_top_k_targets(__a , __a) self.fill_mask_with_duplicate_targets_and_top_k(__a , __a) self.fill_mask_with_multiple_masks(__a , __a) def UpperCAmelCase ( self , __a , __a) -> List[Any]: '''simple docstring''' _UpperCamelCase = tokenizer.get_vocab() _UpperCamelCase = sorted(vocab.keys())[:2] # Pipeline argument _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a , targets=__a) _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''') self.assertEqual( __a , [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ] , ) _UpperCamelCase = {vocab[el] for el in targets} self.assertEqual({el['''token'''] for el in outputs} , __a) _UpperCamelCase = [tokenizer.decode([x]) for x in target_ids] self.assertEqual({el['''token_str'''] for el in outputs} , set(__a)) # Call argument _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a) _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=__a) self.assertEqual( __a , [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ] , ) _UpperCamelCase = {vocab[el] for el in targets} self.assertEqual({el['''token'''] for el in outputs} , __a) _UpperCamelCase = [tokenizer.decode([x]) for x in target_ids] self.assertEqual({el['''token_str'''] for el in outputs} , set(__a)) # Score equivalence _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=__a) _UpperCamelCase = [top_mask['''token_str'''] for top_mask in outputs] _UpperCamelCase = [top_mask['''score'''] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__a) == set(__a): _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=__a) _UpperCamelCase = [top_mask['''score'''] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(__a) , nested_simplify(__a)) # Raises with invalid with self.assertRaises(__a): _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[]) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(__a): _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=['''''']) with self.assertRaises(__a): _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets='''''') def UpperCAmelCase ( self , __a , __a) -> List[Any]: '''simple docstring''' _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a , top_k=2) _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''') self.assertEqual( __a , [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ] , ) _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a) _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2) self.assertEqual( __a , [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ] , ) self.assertEqual(nested_simplify(__a) , nested_simplify(__a)) def UpperCAmelCase ( self , __a , __a) -> Any: '''simple docstring''' _UpperCamelCase = tokenizer.get_vocab() _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a) # top_k=2, ntargets=3 _UpperCamelCase = sorted(vocab.keys())[:3] _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 , targets=__a) # If we use the most probably targets, and filter differently, we should still # have the same results _UpperCamelCase = [el['''token_str'''] for el in sorted(__a , key=lambda __a: x["score"] , reverse=__a)] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(__a).issubset(__a): _UpperCamelCase = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=3 , targets=__a) # They should yield exactly the same result self.assertEqual(nested_simplify(__a) , nested_simplify(__a)) def UpperCAmelCase ( self , __a , __a) -> Dict: '''simple docstring''' _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a) _UpperCamelCase = tokenizer.get_vocab() # String duplicates + id duplicates _UpperCamelCase = sorted(vocab.keys())[:3] _UpperCamelCase = [targets[0], targets[1], targets[0], targets[2], targets[1]] _UpperCamelCase = fill_masker(F'''My name is {tokenizer.mask_token}''' , targets=__a , top_k=10) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(__a) , 3) def UpperCAmelCase ( self , __a , __a) -> Any: '''simple docstring''' _UpperCamelCase = FillMaskPipeline(model=__a , tokenizer=__a) _UpperCamelCase = fill_masker( F'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''' , top_k=2) self.assertEqual( __a , [ [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ], [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ], [ {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, {'''sequence''': ANY(__a), '''score''': ANY(__a), '''token''': ANY(__a), '''token_str''': ANY(__a)}, ], ] , )
100
"""simple docstring""" import numpy class _UpperCAmelCase: def __init__( self , __a , __a) -> None: '''simple docstring''' _UpperCamelCase = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. _UpperCamelCase = numpy.random.rand( self.input_array.shape[1] , 4) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. _UpperCamelCase = numpy.random.rand( 4 , 3) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. _UpperCamelCase = numpy.random.rand(3 , 1) # Real output values provided. _UpperCamelCase = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. _UpperCamelCase = numpy.zeros(output_array.shape) def UpperCAmelCase ( self) -> numpy.ndarray: '''simple docstring''' _UpperCamelCase = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights)) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return self.layer_between_second_hidden_layer_and_output def UpperCAmelCase ( self) -> None: '''simple docstring''' _UpperCamelCase = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , ) _UpperCamelCase = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , ) _UpperCamelCase = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def UpperCAmelCase ( self , __a , __a , __a) -> None: '''simple docstring''' for iteration in range(1 , iterations + 1): _UpperCamelCase = self.feedforward() self.back_propagation() if give_loss: _UpperCamelCase = numpy.mean(numpy.square(output - self.feedforward())) print(F'''Iteration {iteration} Loss: {loss}''') def UpperCAmelCase ( self , __a) -> int: '''simple docstring''' _UpperCamelCase = input_arr _UpperCamelCase = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights)) _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) _UpperCamelCase = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return int(self.layer_between_second_hidden_layer_and_output > 0.6) def lowerCamelCase__ ( __snake_case ) -> numpy.ndarray: """simple docstring""" return 1 / (1 + numpy.exp(-value )) def lowerCamelCase__ ( __snake_case ) -> numpy.ndarray: """simple docstring""" return (value) * (1 - (value)) def lowerCamelCase__ ( ) -> int: """simple docstring""" _UpperCamelCase = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=numpy.floataa, ) # True output values for the given input values. _UpperCamelCase = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.floataa ) # Calling neural network class. _UpperCamelCase = TwoHiddenLayerNeuralNetwork( input_array=__snake_case, output_array=__snake_case ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=__snake_case, iterations=10, give_loss=__snake_case ) return neural_network.predict(numpy.array(([1, 1, 1]), dtype=numpy.floataa ) ) if __name__ == "__main__": example()
100
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : Dict = ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' )) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' ,type=lowerCamelCase_ ,default=1 ,help='''Number of TPU cores to use (1 or 8).''') # positional parser.add_argument( '''training_script''' ,type=lowerCamelCase_ ,help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) ,) # rest from the training program parser.add_argument('''training_script_args''' ,nargs=lowerCamelCase_) return parser.parse_args() def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : str = parse_args() # Import training_script as a module. lowerCAmelCase__ : List[Any] = Path(args.training_script) sys.path.append(str(script_fpath.parent.resolve())) lowerCAmelCase__ : List[Any] = script_fpath.stem lowerCAmelCase__ : List[str] = importlib.import_module(lowerCamelCase_) # Patch sys.argv lowerCAmelCase__ : List[Any] = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores)] xmp.spawn(mod._mp_fn ,args=() ,nprocs=args.num_cores) if __name__ == "__main__": main()
129
def lowerCAmelCase__ ( lowerCamelCase_ : str): '''simple docstring''' lowerCAmelCase__ : Any = [0] * len(lowerCamelCase_) for i in range(1 ,len(lowerCamelCase_)): # use last results for better performance - dynamic programming lowerCAmelCase__ : Optional[Any] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: lowerCAmelCase__ : Optional[int] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 lowerCAmelCase__ : Union[str, Any] = j return prefix_result def lowerCAmelCase__ ( lowerCamelCase_ : str): '''simple docstring''' return max(prefix_function(lowerCamelCase_)) if __name__ == "__main__": import doctest doctest.testmod()
129
1
from abc import ABC, abstractmethod from argparse import ArgumentParser class a ( __lowerCAmelCase ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase ( lowerCAmelCase_ ) -> Optional[Any]: raise NotImplementedError() @abstractmethod def UpperCAmelCase ( self ) -> Any: raise NotImplementedError()
81
from math import isqrt def snake_case ( snake_case__ :int) -> list[int]: _A = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , snake_case__ , snake_case__): _A = False return [i for i in range(2 , snake_case__) if is_prime[i]] def snake_case ( snake_case__ :int = 10**8) -> int: _A = calculate_prime_numbers(max_number // 2) _A = 0 _A = 0 _A = len(snake_case__) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'''{solution() = }''')
81
1
'''simple docstring''' from math import sqrt def _lowerCamelCase ( lowercase : int ) -> int: _a = 0 for i in range(1 , int(sqrt(lowercase ) + 1 ) ): if n % i == 0 and i != sqrt(lowercase ): total += i + n // i elif i == sqrt(lowercase ): total += i return total - n def _lowerCamelCase ( lowercase : int = 1_0000 ) -> int: _a = sum( i for i in range(1 , lowercase ) if sum_of_divisors(sum_of_divisors(lowercase ) ) == i and sum_of_divisors(lowercase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
63
"""simple docstring""" import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class lowerCamelCase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 13 , SCREAMING_SNAKE_CASE = 64 , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = 3 , SCREAMING_SNAKE_CASE = 3 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 128 , SCREAMING_SNAKE_CASE=[16, 32, 64, 128] , SCREAMING_SNAKE_CASE = 7 , SCREAMING_SNAKE_CASE = 4 , SCREAMING_SNAKE_CASE = 37 , SCREAMING_SNAKE_CASE = "gelu" , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 10 , SCREAMING_SNAKE_CASE = 0.02 , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 128 , SCREAMING_SNAKE_CASE = [2, 2, 2, 2] , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = 2 , ): """simple docstring""" snake_case : int = parent snake_case : List[Any] = batch_size snake_case : List[str] = image_size snake_case : int = patch_size snake_case : int = num_channels snake_case : Any = is_training snake_case : int = use_labels snake_case : Optional[Any] = hidden_size snake_case : str = num_hidden_layers snake_case : Optional[int] = num_attention_heads snake_case : Union[str, Any] = intermediate_size snake_case : Dict = hidden_act snake_case : Any = hidden_dropout_prob snake_case : Optional[Any] = attention_probs_dropout_prob snake_case : List[Any] = type_sequence_label_size snake_case : Optional[Any] = initializer_range snake_case : Any = encoder_stride snake_case : Tuple = num_attention_outputs snake_case : Dict = embed_dim snake_case : Optional[Any] = embed_dim + 1 snake_case : Any = resolution snake_case : int = depths snake_case : int = hidden_sizes snake_case : int = dim snake_case : Tuple = mlp_expansion_ratio def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case : Optional[int] = None if self.use_labels: snake_case : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : str = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self ): """simple docstring""" return EfficientFormerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case : str = TFEfficientFormerModel(config=SCREAMING_SNAKE_CASE ) snake_case : Optional[Any] = model(SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" snake_case : Optional[int] = self.type_sequence_label_size snake_case : Tuple = TFEfficientFormerForImageClassification(SCREAMING_SNAKE_CASE ) snake_case : List[Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case : Tuple = 1 snake_case : Any = TFEfficientFormerForImageClassification(SCREAMING_SNAKE_CASE ) snake_case : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case : Union[str, Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Any = self.prepare_config_and_inputs() snake_case , snake_case , snake_case : Tuple = config_and_inputs snake_case : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase__ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): a__ : Dict = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) a__ : int = ( { """feature-extraction""": TFEfficientFormerModel, """image-classification""": ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) a__ : int = False a__ : List[str] = False a__ : Union[str, Any] = False a__ : Optional[Any] = False a__ : str = False def lowerCamelCase_ ( self ): """simple docstring""" snake_case : List[Any] = TFEfficientFormerModelTester(self ) snake_case : Dict = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=37 ) def lowerCamelCase_ ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="EfficientFormer does not use inputs_embeds" ) def lowerCamelCase_ ( self ): """simple docstring""" pass @unittest.skip(reason="EfficientFormer does not support input and output embeddings" ) def lowerCamelCase_ ( self ): """simple docstring""" pass def lowerCamelCase_ ( self ): """simple docstring""" snake_case , snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : str = model_class(SCREAMING_SNAKE_CASE ) snake_case : Dict = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : Optional[int] = [*signature.parameters.keys()] snake_case : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self ): """simple docstring""" def check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): snake_case : List[str] = model_class(SCREAMING_SNAKE_CASE ) snake_case : Any = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , training=SCREAMING_SNAKE_CASE ) snake_case : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case : List[Any] = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) if hasattr(self.model_tester , "encoder_seq_length" ): snake_case : List[Any] = self.model_tester.encoder_seq_length if hasattr(self.model_tester , "chunk_length" ) and self.model_tester.chunk_length > 1: snake_case : Optional[int] = seq_length * self.model_tester.chunk_length else: snake_case : List[Any] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: snake_case : List[Any] = outputs.decoder_hidden_states self.asseretIsInstance(SCREAMING_SNAKE_CASE , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) snake_case : Tuple = getattr(self.model_tester , "seq_length" , SCREAMING_SNAKE_CASE ) snake_case : Tuple = getattr(self.model_tester , "decoder_seq_length" , SCREAMING_SNAKE_CASE ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) snake_case , snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : 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"] snake_case : Optional[int] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ): """simple docstring""" snake_case : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) @unittest.skip(reason="EfficientFormer does not implement masked image modeling yet" ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) @slow def lowerCamelCase_ ( self ): """simple docstring""" for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : str = TFEfficientFormerModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case , snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() snake_case : str = True snake_case : Tuple = getattr(self.model_tester , "seq_length" , SCREAMING_SNAKE_CASE ) snake_case : Optional[int] = getattr(self.model_tester , "encoder_seq_length" , SCREAMING_SNAKE_CASE ) snake_case : Optional[Any] = getattr(self.model_tester , "key_length" , SCREAMING_SNAKE_CASE ) snake_case : Tuple = getattr(self.model_tester , "chunk_length" , SCREAMING_SNAKE_CASE ) if chunk_length is not None and hasattr(self.model_tester , "num_hashes" ): snake_case : Optional[int] = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: snake_case : Optional[int] = True snake_case : List[Any] = False snake_case : Optional[int] = True snake_case : List[str] = model_class(SCREAMING_SNAKE_CASE ) snake_case : List[str] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , training=SCREAMING_SNAKE_CASE ) snake_case : int = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case : Tuple = True snake_case : List[str] = model_class(SCREAMING_SNAKE_CASE ) snake_case : int = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , training=SCREAMING_SNAKE_CASE ) snake_case : Any = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case , snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model snake_case : Union[str, Any] = model_class(SCREAMING_SNAKE_CASE ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes snake_case : Optional[Any] = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=SCREAMING_SNAKE_CASE ) for key, val in model.input_signature.items() if key in model.dummy_inputs } snake_case : Any = model(SCREAMING_SNAKE_CASE ) self.assertTrue(outputs_dict is not None ) def UpperCamelCase__ ( ): snake_case : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class lowerCamelCase__ ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self ): """simple docstring""" return ( EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300" ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self ): """simple docstring""" snake_case : str = TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300" ) snake_case : List[Any] = self.default_image_processor snake_case : Optional[Any] = prepare_img() snake_case : int = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="tf" ) # forward pass snake_case : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) # verify the logits snake_case : int = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) snake_case : Dict = tf.constant([-0.05_55, 0.48_25, -0.08_52] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Optional[int] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( "snap-research/efficientformer-l1-300" ) snake_case : int = self.default_image_processor snake_case : List[Any] = prepare_img() snake_case : Optional[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="tf" ) # forward pass snake_case : Any = model(**SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE ) # verify the logits snake_case : Any = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE ) snake_case : Optional[int] = tf.constant([-0.13_12, 0.43_53, -1.04_99] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) )
148
0
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class __A : def __init__( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int]=14 , UpperCAmelCase_ : Any=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Optional[Any]=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Tuple=4 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : str=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Optional[Any]=512 , UpperCAmelCase_ : List[str]=0.02 , ): lowerCAmelCase : Dict = parent lowerCAmelCase : Optional[Any] = batch_size lowerCAmelCase : List[Any] = seq_length lowerCAmelCase : int = is_training lowerCAmelCase : str = use_input_mask lowerCAmelCase : int = use_token_type_ids lowerCAmelCase : List[Any] = use_labels lowerCAmelCase : str = vocab_size lowerCAmelCase : Optional[Any] = hidden_size lowerCAmelCase : Dict = rotary_dim lowerCAmelCase : int = num_hidden_layers lowerCAmelCase : Optional[int] = num_attention_heads lowerCAmelCase : Optional[int] = intermediate_size lowerCAmelCase : Any = hidden_act lowerCAmelCase : Tuple = hidden_dropout_prob lowerCAmelCase : Optional[int] = attention_probs_dropout_prob lowerCAmelCase : int = max_position_embeddings lowerCAmelCase : Dict = initializer_range lowerCAmelCase : int = None lowerCAmelCase : List[Any] = vocab_size - 1 lowerCAmelCase : Dict = vocab_size - 1 lowerCAmelCase : Union[str, Any] = vocab_size - 1 def lowercase__ ( self : str ): lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase : Optional[Any] = None if self.use_input_mask: lowerCAmelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase : Dict = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowercase__ ( self : Dict ): lowerCAmelCase : int = self.prepare_config_and_inputs() lowerCAmelCase : List[str] = config_and_inputs lowerCAmelCase : List[Any] = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def lowercase__ ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple ): lowerCAmelCase : Optional[int] = 20 lowerCAmelCase : List[Any] = model_class_name(UpperCAmelCase_ ) lowerCAmelCase : Union[str, Any] = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) lowerCAmelCase : List[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) lowerCAmelCase : Union[str, Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowerCAmelCase : Optional[int] = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) lowerCAmelCase : Tuple = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) lowerCAmelCase : List[Any] = model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) lowerCAmelCase : List[Any] = model(UpperCAmelCase_ ) lowerCAmelCase : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def lowercase__ ( self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] ): lowerCAmelCase : List[str] = 20 lowerCAmelCase : Any = model_class_name(UpperCAmelCase_ ) lowerCAmelCase : Tuple = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) lowerCAmelCase : Optional[Any] = model.init_cache(input_ids.shape[0] , UpperCAmelCase_ ) lowerCAmelCase : List[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) lowerCAmelCase : Any = model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) lowerCAmelCase : int = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) lowerCAmelCase : Dict = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) lowerCAmelCase : Union[str, Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) lowerCAmelCase : List[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class __A ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): lowerCAmelCase_ : Union[str, Any] = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () lowerCAmelCase_ : Tuple = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowercase__ ( self : List[Any] ): lowerCAmelCase : Tuple = FlaxGPTJModelTester(self ) def lowercase__ ( self : int ): for model_class_name in self.all_model_classes: lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowercase__ ( self : Optional[Any] ): for model_class_name in self.all_model_classes: lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @tooslow def lowercase__ ( self : Optional[int] ): lowerCAmelCase : Tuple = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) lowerCAmelCase : int = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ ) lowerCAmelCase : Tuple = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) lowerCAmelCase : List[str] = False lowerCAmelCase : List[str] = model.config.eos_token_id lowerCAmelCase : Optional[Any] = jax.jit(model.generate ) lowerCAmelCase : List[str] = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences lowerCAmelCase : Optional[Any] = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) lowerCAmelCase : Union[str, Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @is_pt_flax_cross_test def lowercase__ ( self : Optional[int] ): lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowerCAmelCase : Optional[Any] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) lowerCAmelCase : Optional[Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCAmelCase : Any = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCAmelCase : Union[str, Any] = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) lowerCAmelCase : Dict = pt_inputs['input_ids'].shape lowerCAmelCase : Tuple = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): lowerCAmelCase : Any = 0 lowerCAmelCase : List[Any] = 1 lowerCAmelCase : List[str] = 0 lowerCAmelCase : int = 1 lowerCAmelCase : Optional[Any] = pt_model_class(UpperCAmelCase_ ).eval() lowerCAmelCase : int = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) lowerCAmelCase : List[str] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_ ) lowerCAmelCase : Optional[Any] = fx_state with torch.no_grad(): lowerCAmelCase : List[str] = pt_model(**UpperCAmelCase_ ).to_tuple() lowerCAmelCase : Optional[int] = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_ ) lowerCAmelCase : List[str] = model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_ ) lowerCAmelCase : str = fx_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def lowercase__ ( self : List[str] ): lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs lowerCAmelCase : List[str] = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCAmelCase : Optional[int] = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCAmelCase : str = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) lowerCAmelCase : Union[str, Any] = pt_model_class(UpperCAmelCase_ ).eval() lowerCAmelCase : Optional[int] = model_class(UpperCAmelCase_ , dtype=jnp.floataa ) lowerCAmelCase : Dict = load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params ) lowerCAmelCase : List[str] = pt_inputs['input_ids'].shape lowerCAmelCase : Any = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCAmelCase_ ): lowerCAmelCase : List[str] = 0 lowerCAmelCase : Optional[Any] = 1 lowerCAmelCase : List[Any] = 0 lowerCAmelCase : Union[str, Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): lowerCAmelCase : List[Any] = pt_model(**UpperCAmelCase_ ).to_tuple() lowerCAmelCase : int = fx_model(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_ ) lowerCAmelCase : List[str] = pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_ ) with torch.no_grad(): lowerCAmelCase : Tuple = pt_model_loaded(**UpperCAmelCase_ ).to_tuple() self.assertEqual( len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def lowercase__ ( self : Dict ): for model_class_name in self.all_model_classes: lowerCAmelCase : str = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) lowerCAmelCase : List[str] = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase_ )
356
from collections.abc import Sequence def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> float: '''simple docstring''' return sum(c * (x**i) for i, c in enumerate(_UpperCAmelCase ) ) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> float: '''simple docstring''' lowerCAmelCase : Optional[int] = 0.0 for coeff in reversed(_UpperCAmelCase ): lowerCAmelCase : Union[str, Any] = result * x + coeff return result if __name__ == "__main__": __A : Optional[int] = (0.0, 0.0, 5.0, 9.3, 7.0) __A : str = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
323
0
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int ): """simple docstring""" 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...""") lowerCamelCase__ = int(input("""Enter number: """).strip()) print(F"""{number} is {'' if perfect(number) else 'not '}a Perfect Number.""")
302
from __future__ import annotations lowerCamelCase__ = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class SCREAMING_SNAKE_CASE : def __init__( self : Tuple , __lowercase : dict[str, list[str]] , __lowercase : str ): '''simple docstring''' __a = graph # mapping node to its parent in resulting breadth first tree __a = {} __a = source_vertex def UpperCamelCase_ ( self : Any ): '''simple docstring''' __a = {self.source_vertex} __a = None __a = [self.source_vertex] # first in first out queue while queue: __a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowercase ) __a = vertex queue.append(__lowercase ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex __a = self.parent.get(__lowercase ) if target_vertex_parent is None: __a = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowercase ) return self.shortest_path(__lowercase ) + F"->{target_vertex}" if __name__ == "__main__": lowerCamelCase__ = Graph(graph, """G""") g.breath_first_search() print(g.shortest_path("""D""")) print(g.shortest_path("""G""")) print(g.shortest_path("""Foo"""))
302
1
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @property def _a ( self ): torch.manual_seed(0 ) UpperCamelCase_: str = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _a ( self ): torch.manual_seed(0 ) UpperCamelCase_: Union[str, Any] = VQModel( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _a ( self ): torch.manual_seed(0 ) UpperCamelCase_: str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Any = self.dummy_uncond_unet UpperCamelCase_: List[str] = DDIMScheduler() UpperCamelCase_: Union[str, Any] = self.dummy_vq_model UpperCamelCase_: List[Any] = LDMPipeline(unet=_lowerCamelCase , vqvae=_lowerCamelCase , scheduler=_lowerCamelCase ) ldm.to(_lowerCamelCase ) ldm.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: Dict = torch.manual_seed(0 ) UpperCamelCase_: Dict = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type='numpy' ).images UpperCamelCase_: Dict = torch.manual_seed(0 ) UpperCamelCase_: List[Any] = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type='numpy' , return_dict=_lowerCamelCase )[0] UpperCamelCase_: Tuple = image[0, -3:, -3:, -1] UpperCamelCase_: Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) UpperCamelCase_: List[str] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) UpperCamelCase_: Union[str, Any] = 1e-2 if torch_device != '''mps''' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Optional[int] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(_lowerCamelCase ) ldm.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: Tuple = torch.manual_seed(0 ) UpperCamelCase_: List[Any] = ldm(generator=_lowerCamelCase , num_inference_steps=5 , output_type='numpy' ).images UpperCamelCase_: Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) UpperCamelCase_: List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) UpperCamelCase_: str = 1e-2 if torch_device != '''mps''' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
352
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : Tuple = logging.get_logger(__name__) A_ : Dict = { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/config.json', # See all XGLM models at https://huggingface.co/models?filter=xglm } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Tuple ='''xglm''' a : List[Any] =['''past_key_values'''] a : Union[str, Any] ={ '''num_attention_heads''': '''attention_heads''', '''hidden_size''': '''d_model''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _lowerCamelCase=2_5_6_0_0_8 , _lowerCamelCase=2_0_4_8 , _lowerCamelCase=1_0_2_4 , _lowerCamelCase=4_0_9_6 , _lowerCamelCase=2_4 , _lowerCamelCase=1_6 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0_2 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , _lowerCamelCase=2 , **_lowerCamelCase , ): UpperCamelCase_: Optional[Any] = vocab_size UpperCamelCase_: Optional[int] = max_position_embeddings UpperCamelCase_: List[str] = d_model UpperCamelCase_: List[Any] = ffn_dim UpperCamelCase_: List[Any] = num_layers UpperCamelCase_: List[Any] = attention_heads UpperCamelCase_: Tuple = activation_function UpperCamelCase_: Tuple = dropout UpperCamelCase_: Tuple = attention_dropout UpperCamelCase_: Optional[Any] = activation_dropout UpperCamelCase_: List[str] = layerdrop UpperCamelCase_: Any = init_std UpperCamelCase_: Any = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase_: Union[str, Any] = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
292
0
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowerCAmelCase ( lowerCAmelCase_ :NDArray[floataa] , lowerCAmelCase_ :NDArray[floataa] , lowerCAmelCase_ :list[int] , lowerCAmelCase_ :int , )->list[float]: '''simple docstring''' snake_case_ , snake_case_ = coefficient_matrix.shape snake_case_ , snake_case_ = constant_matrix.shape if rowsa != colsa: snake_case_ = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(lowerCAmelCase_ ) if colsa != 1: snake_case_ = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(lowerCAmelCase_ ) if rowsa != rowsa: snake_case_ = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) != rowsa: snake_case_ = ( "Number of initial values must be equal to number of rows in coefficient " F'''matrix but received {len(lowerCAmelCase_ )} and {rowsa}''' ) raise ValueError(lowerCAmelCase_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) snake_case_ = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) snake_case_ , snake_case_ = table.shape strictly_diagonally_dominant(lowerCAmelCase_ ) # Iterates the whole matrix for given number of times for _ in range(lowerCAmelCase_ ): snake_case_ = [] for row in range(lowerCAmelCase_ ): snake_case_ = 0 for col in range(lowerCAmelCase_ ): if col == row: snake_case_ = table[row][col] elif col == cols - 1: snake_case_ = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] snake_case_ = (temp + val) / denom new_val.append(lowerCAmelCase_ ) snake_case_ = new_val return [float(lowerCAmelCase_ ) for i in new_val] def _lowerCAmelCase ( lowerCAmelCase_ :NDArray[floataa] )->bool: '''simple docstring''' snake_case_ , snake_case_ = table.shape snake_case_ = True for i in range(0 , lowerCAmelCase_ ): snake_case_ = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
159
def _lowerCAmelCase ( lowerCAmelCase_ :int = 1_000 )->int: '''simple docstring''' snake_case_ , snake_case_ = 1, 1 snake_case_ = 2 while True: snake_case_ = 0 snake_case_ = fa + fa snake_case_ , snake_case_ = fa, f index += 1 for _ in str(lowerCAmelCase_ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
159
1
def lowerCAmelCase_ ( snake_case_,snake_case_ = " " ): _A : List[Any] = [] _A : Optional[Any] = 0 for index, char in enumerate(snake_case_ ): if char == separator: split_words.append(string[last_index:index] ) _A : str = index + 1 elif index + 1 == len(snake_case_ ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
367
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def lowerCAmelCase_ ( snake_case_ = "mumbai" ): _A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ): _A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
0
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a__ : Optional[int] =[ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): """simple docstring""" def _lowerCamelCase ( self : int , __A : str , __A : bool , __A : str = None , __A : list = None ): __UpperCamelCase = None __UpperCamelCase = os.path.abspath(os.path.join('examples' , 'by_feature' ) ) __UpperCamelCase = os.path.abspath('examples' ) for item in os.listdir(__A ): if item not in EXCLUDE_EXAMPLES: __UpperCamelCase = os.path.join(__A , __A ) if os.path.isfile(__A ) and ".py" in item_path: with self.subTest( tested_script=__A , feature_script=__A , tested_section='main()' if parser_only else 'training_function()' , ): __UpperCamelCase = compare_against_test( os.path.join(__A , __A ) , __A , __A , __A ) __UpperCamelCase = '\n'.join(__A ) if special_strings is not None: for string in special_strings: __UpperCamelCase = diff.replace(__A , '' ) self.assertEqual(__A , '' ) def _lowerCamelCase ( self : int ): self.one_complete_example('complete_nlp_example.py' , __A ) self.one_complete_example('complete_nlp_example.py' , __A ) def _lowerCamelCase ( self : List[str] ): __UpperCamelCase = os.path.abspath(os.path.join('examples' , 'cv_example.py' ) ) __UpperCamelCase = [ ' ' * 1_6 + '{\n\n', ' ' * 2_0 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 2_0 + '"f1": eval_metric["f1"],\n\n', ' ' * 2_0 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 2_0 + '"epoch": epoch,\n\n', ' ' * 1_6 + '},\n\n', ' ' * 1_6 + 'step=epoch,\n', ' ' * 1_2, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , __A , __A , __A ) self.one_complete_example('complete_cv_example.py' , __A , __A , __A ) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] =False @classmethod def _lowerCamelCase ( cls : Any ): super().setUpClass() __UpperCamelCase = tempfile.mkdtemp() __UpperCamelCase = os.path.join(cls._tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __UpperCamelCase = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def _lowerCamelCase ( cls : Any ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def _lowerCamelCase ( self : Any ): __UpperCamelCase = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0' ) ) ) def _lowerCamelCase ( self : str ): __UpperCamelCase = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __UpperCamelCase = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2' ) ) ) def _lowerCamelCase ( self : List[str] ): __UpperCamelCase = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __UpperCamelCase = run_command(self._launch_args + testargs , return_stdout=__A ) self.assertNotIn('epoch 0:' , __A ) self.assertIn('epoch 1:' , __A ) def _lowerCamelCase ( self : List[Any] ): __UpperCamelCase = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __UpperCamelCase = run_command(self._launch_args + testargs , return_stdout=__A ) if torch.cuda.is_available(): __UpperCamelCase = torch.cuda.device_count() else: __UpperCamelCase = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , __A ) self.assertIn('epoch 1:' , __A ) else: self.assertIn('epoch 0:' , __A ) self.assertIn('epoch 1:' , __A ) @slow def _lowerCamelCase ( self : Tuple ): __UpperCamelCase = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'} ): __UpperCamelCase = run_command(self._launch_args + testargs , return_stdout=__A ) __UpperCamelCase = re.findall('({.+})' , __A ) __UpperCamelCase = [r for r in results if 'accuracy' in r][-1] __UpperCamelCase = ast.literal_eval(__A ) self.assertGreaterEqual(results['accuracy'] , 0.75 ) def _lowerCamelCase ( self : Dict ): __UpperCamelCase = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def _lowerCamelCase ( self : List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __UpperCamelCase = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(__A , 'tracking' ) ) ) def _lowerCamelCase ( self : Optional[int] ): __UpperCamelCase = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs ) def _lowerCamelCase ( self : List[Any] ): __UpperCamelCase = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs )
53
'''simple docstring''' import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class snake_case ( __lowerCamelCase ): """simple docstring""" def __init__( self : Any , __A : Dict , __A : str , __A : List[Any]=1_0_2_4 , __A : Tuple=1_0_2_4 , __A : str=3.6 ): __UpperCamelCase = tokenizer __UpperCamelCase = tokenizer.bos_token_id __UpperCamelCase = dataset __UpperCamelCase = seq_length __UpperCamelCase = seq_length * chars_per_token * num_of_sequences def __iter__( self : Any ): __UpperCamelCase = iter(self.dataset ) __UpperCamelCase = True while more_examples: __UpperCamelCase , __UpperCamelCase = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(__A )['content'] ) buffer_len += len(buffer[-1] ) except StopIteration: __UpperCamelCase = False break __UpperCamelCase = tokenizer(__A , truncation=__A )['input_ids'] __UpperCamelCase = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(__A ) , self.seq_length ): __UpperCamelCase = all_token_ids[i : i + self.seq_length] if len(__A ) == self.seq_length: yield torch.tensor(__A ) def lowercase__ ( __lowercase : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase = {'streaming': True} __UpperCamelCase = load_dataset(args.dataset_name , split='train' , **__lowercase ) __UpperCamelCase = ConstantLengthDataset(__lowercase , __lowercase , seq_length=args.seq_length ) __UpperCamelCase = DataLoader(__lowercase , batch_size=args.batch_size ) return eval_dataloader def lowercase__ ( __lowercase : Tuple ) -> Optional[Any]: """simple docstring""" model.eval() __UpperCamelCase = [] for step, batch in enumerate(__lowercase ): with torch.no_grad(): __UpperCamelCase = model(__lowercase , labels=__lowercase ) __UpperCamelCase = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(__lowercase ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __UpperCamelCase = torch.mean(torch.cat(__lowercase ) ) try: __UpperCamelCase = torch.exp(__lowercase ) except OverflowError: __UpperCamelCase = float('inf' ) return loss.item(), perplexity.item() # Setup Accelerator a__ : int =Accelerator() # Parse configuration a__ : Dict =HfArgumentParser(EvaluationArguments) a__ : Union[str, Any] =parser.parse_args() set_seed(args.seed) # Logging a__ : List[Any] =logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer a__ : Union[str, Any] =AutoModelForCausalLM.from_pretrained(args.model_ckpt) a__ : List[Any] =AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader a__ : Union[str, Any] =create_dataloader(args) # Prepare everything with our `accelerator`. a__ , a__ : List[str] =accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') a__ , a__ : Any =evaluate(args) logger.info(f'loss/eval: {eval_loss}, perplexity: {perplexity}')
53
1
import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCamelCase : List[Any] = { "facebook/maskformer-swin-base-ade": ( "https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json" ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCamelCase : Any = logging.get_logger(__name__) class A( __lowercase ): '''simple docstring''' UpperCamelCase = '''maskformer''' UpperCamelCase = {'''hidden_size''': '''mask_feature_size'''} UpperCamelCase = ['''resnet''', '''swin'''] UpperCamelCase = ['''detr'''] def __init__( self : Optional[int] , A_ : int = 256 , A_ : int = 256 , A_ : float = 0.1 , A_ : bool = False , A_ : Optional[Dict] = None , A_ : Optional[Dict] = None , A_ : float = 0.02 , A_ : float = 1.0 , A_ : float = 1.0 , A_ : float = 1.0 , A_ : float = 20.0 , A_ : Optional[bool] = None , **A_ : Optional[Any] , ) -> int: """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k lowerCamelCase_ = SwinConfig( image_size=384 , in_channels=3 , patch_size=4 , embed_dim=128 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowerCamelCase_ = backbone_config.pop('model_type' ) lowerCamelCase_ = CONFIG_MAPPING[backbone_model_type] lowerCamelCase_ = config_class.from_dict(UpperCAmelCase__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. """ f"""Supported model types: {",".join(self.backbones_supported )}""" ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 lowerCamelCase_ = DetrConfig() else: # verify that the decoder is supported lowerCamelCase_ = ( decoder_config.pop('model_type' ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f"""Transformer Decoder {decoder_type} not supported, please use one of""" f""" {",".join(self.decoders_supported )}""" ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): lowerCamelCase_ = CONFIG_MAPPING[decoder_type] lowerCamelCase_ = config_class.from_dict(UpperCAmelCase__ ) lowerCamelCase_ = backbone_config lowerCamelCase_ = decoder_config # main feature dimension for the model lowerCamelCase_ = fpn_feature_size lowerCamelCase_ = mask_feature_size # initializer lowerCamelCase_ = init_std lowerCamelCase_ = init_xavier_std # Hungarian matcher && loss lowerCamelCase_ = cross_entropy_weight lowerCamelCase_ = dice_weight lowerCamelCase_ = mask_weight lowerCamelCase_ = use_auxiliary_loss lowerCamelCase_ = no_object_weight lowerCamelCase_ = output_auxiliary_logits lowerCamelCase_ = self.decoder_config.encoder_attention_heads lowerCamelCase_ = self.decoder_config.num_hidden_layers super().__init__(**UpperCAmelCase__ ) @classmethod def a__ ( cls : Tuple , A_ : PretrainedConfig , A_ : PretrainedConfig , **A_ : List[str] ) -> Union[str, Any]: """simple docstring""" return cls( backbone_config=UpperCAmelCase__ , decoder_config=UpperCAmelCase__ , **UpperCAmelCase__ , ) def a__ ( self : Optional[int] ) -> Dict[str, any]: """simple docstring""" lowerCamelCase_ = copy.deepcopy(self.__dict__ ) lowerCamelCase_ = self.backbone_config.to_dict() lowerCamelCase_ = self.decoder_config.to_dict() lowerCamelCase_ = self.__class__.model_type return output
361
import math def _SCREAMING_SNAKE_CASE ( lowercase : int ): '''simple docstring''' lowerCamelCase_ = 0 lowerCamelCase_ = 0 while num > 0: lowerCamelCase_ = num % 8 lowerCamelCase_ = octal + (remainder * math.floor(math.pow(10 , lowercase ) )) counter += 1 lowerCamelCase_ = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"""0o{int(lowercase )}""" def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' print('\n2 in octal is:' ) print(decimal_to_octal(2 ) ) # = 2 print('\n8 in octal is:' ) print(decimal_to_octal(8 ) ) # = 10 print('\n65 in octal is:' ) print(decimal_to_octal(65 ) ) # = 101 print('\n216 in octal is:' ) print(decimal_to_octal(2_16 ) ) # = 330 print('\n512 in octal is:' ) print(decimal_to_octal(5_12 ) ) # = 1000 print('\n' ) if __name__ == "__main__": main()
208
0
def __lowercase ( ) -> int: '''simple docstring''' return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(_SCREAMING_SNAKE_CASE , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] if __name__ == "__main__": print(F'''{solution() = }''')
296
from collections import defaultdict from math import gcd def __lowercase ( _SCREAMING_SNAKE_CASE = 1_50_00_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , _SCREAMING_SNAKE_CASE , 2 ): if gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) > 1: continue SCREAMING_SNAKE_CASE = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'''{solution() = }''')
296
1
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput _A = 'scheduler_config.json' class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = 1 UpperCAmelCase__ : Union[str, Any] = 2 UpperCAmelCase__ : List[Any] = 3 UpperCAmelCase__ : Optional[int] = 4 UpperCAmelCase__ : Dict = 5 @dataclass class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : jnp.ndarray class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str = SCHEDULER_CONFIG_NAME UpperCAmelCase__ : str = ["dtype"] UpperCAmelCase__ : int = [] UpperCAmelCase__ : List[Any] = True @classmethod def _a ( cls , A_ = None , A_ = None , A_=False , **A_ , ) -> List[Any]: __UpperCamelCase , __UpperCamelCase =cls.load_config( pretrained_model_name_or_path=A_ , subfolder=A_ , return_unused_kwargs=A_ , **A_ , ) __UpperCamelCase , __UpperCamelCase =cls.from_config(A_ , return_unused_kwargs=A_ , **A_ ) if hasattr(A_ , 'create_state' ) and getattr(A_ , 'has_state' , A_ ): __UpperCamelCase =scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def _a ( self , A_ , A_ = False , **A_ ) -> Dict: self.save_config(save_directory=A_ , push_to_hub=A_ , **A_ ) @property def _a ( self ) -> Dict: return self._get_compatibles() @classmethod def _a ( cls ) -> List[Any]: __UpperCamelCase =list(set([cls.__name__] + cls._compatibles ) ) __UpperCamelCase =importlib.import_module(__name__.split('.' )[0] ) __UpperCamelCase =[ getattr(A_ , A_ ) for c in compatible_classes_str if hasattr(A_ , A_ ) ] return compatible_classes def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : Tuple[int] ): assert len(SCREAMING_SNAKE_CASE__ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(SCREAMING_SNAKE_CASE__ ) - x.ndim) ) , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.999 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=jnp.floataa ): def alpha_bar(SCREAMING_SNAKE_CASE__ : List[str] ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 __UpperCamelCase =[] for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =i / num_diffusion_timesteps __UpperCamelCase =(i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(SCREAMING_SNAKE_CASE__ ) / alpha_bar(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) return jnp.array(SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ ) @flax.struct.dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : jnp.ndarray UpperCAmelCase__ : jnp.ndarray UpperCAmelCase__ : jnp.ndarray @classmethod def _a ( cls , A_ ) -> List[str]: __UpperCamelCase =scheduler.config if config.trained_betas is not None: __UpperCamelCase =jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": __UpperCamelCase =jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __UpperCamelCase =( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __UpperCamelCase =betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( f'beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}' ) __UpperCamelCase =1.0 - betas __UpperCamelCase =jnp.cumprod(A_ , axis=0 ) return cls( alphas=A_ , betas=A_ , alphas_cumprod=A_ , ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : CommonSchedulerState , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray ): __UpperCamelCase =state.alphas_cumprod __UpperCamelCase =alphas_cumprod[timesteps] ** 0.5 __UpperCamelCase =sqrt_alpha_prod.flatten() __UpperCamelCase =broadcast_to_shape_from_left(SCREAMING_SNAKE_CASE__ , original_samples.shape ) __UpperCamelCase =(1 - alphas_cumprod[timesteps]) ** 0.5 __UpperCamelCase =sqrt_one_minus_alpha_prod.flatten() __UpperCamelCase =broadcast_to_shape_from_left(SCREAMING_SNAKE_CASE__ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : CommonSchedulerState , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray ): __UpperCamelCase , __UpperCamelCase =get_sqrt_alpha_prod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : CommonSchedulerState , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray ): __UpperCamelCase , __UpperCamelCase =get_sqrt_alpha_prod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
361
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu _A = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : str=None ): __UpperCamelCase =True while ask_again: __UpperCamelCase =input(SCREAMING_SNAKE_CASE__ ) try: if default is not None and len(SCREAMING_SNAKE_CASE__ ) == 0: return default return convert_value(SCREAMING_SNAKE_CASE__ ) if convert_value is not None else result except Exception: if error_message is not None: print(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str]=[] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : str=0 ): __UpperCamelCase =BulletMenu(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =menu.run(default_choice=SCREAMING_SNAKE_CASE__ ) return convert_value(SCREAMING_SNAKE_CASE__ ) if convert_value is not None else result def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __UpperCamelCase =int(SCREAMING_SNAKE_CASE__ ) return ComputeEnvironment(['LOCAL_MACHINE', 'AMAZON_SAGEMAKER'][value] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =int(SCREAMING_SNAKE_CASE__ ) return DistributedType(['NO', 'MULTI_CPU', 'MULTI_XPU', 'MULTI_GPU', 'MULTI_NPU', 'TPU'][value] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] ): __UpperCamelCase =int(SCREAMING_SNAKE_CASE__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =int(SCREAMING_SNAKE_CASE__ ) return PrecisionType(['no', 'fp16', 'bf16', 'fp8'][value] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): __UpperCamelCase =int(SCREAMING_SNAKE_CASE__ ) return SageMakerDistributedType(['NO', 'DATA_PARALLEL', 'MODEL_PARALLEL'][value] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any ): return {"yes": True, "no": False}[value.lower()] class UpperCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def _a ( self , A_ , A_ , A_ , A_ ) -> Optional[int]: __UpperCamelCase =super()._format_usage(A_ , A_ , A_ , A_ ) __UpperCamelCase =usage.replace('<command> [<args>] ' , '' ) return usage
117
0
import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor lowercase__ : Any = logging.getLogger(__name__) lowercase__ : Union[str, Any] = 5_0 # max width of layer names lowercase__ : Dict = 7_0 # max width of quantizer names def A_ ( snake_case : List[Any] ) -> Optional[Any]: '''simple docstring''' __UpperCamelCase = parser.add_argument_group('''quant_trainer arguments''' ) group.add_argument('''--wprec''' , type=snake_case , default=8 , help='''weight precision''' ) group.add_argument('''--aprec''' , type=snake_case , default=8 , help='''activation precision''' ) group.add_argument('''--quant-per-tensor''' , action='''store_true''' , help='''per tensor weight scaling''' ) group.add_argument('''--quant-disable''' , action='''store_true''' , help='''disable all quantizers''' ) group.add_argument('''--quant-disable-embeddings''' , action='''store_true''' , help='''disable all embeddings quantizers''' ) group.add_argument('''--quant-disable-keyword''' , type=snake_case , nargs='''+''' , help='''disable quantizers by keyword''' ) group.add_argument('''--quant-disable-layer-module''' , type=snake_case , help='''disable quantizers by keyword under layer.''' ) group.add_argument('''--quant-enable-layer-module''' , type=snake_case , help='''enable quantizers by keyword under layer''' ) group.add_argument('''--calibrator''' , default='''max''' , help='''which quantization range calibrator to use''' ) group.add_argument('''--percentile''' , default=snake_case , type=snake_case , help='''percentile for PercentileCalibrator''' ) group.add_argument('''--fuse-qkv''' , action='''store_true''' , help='''use the same scale factor for qkv''' ) group.add_argument('''--clip-gelu''' , metavar='''N''' , type=snake_case , help='''clip gelu output maximum value to N''' ) group.add_argument( '''--recalibrate-weights''' , action='''store_true''' , help=( '''recalibrate weight amaxes by taking the max of the weights.''' ''' amaxes will be computed with the current quantization granularity (axis).''' ) , ) def A_ ( snake_case : int ) -> Any: '''simple docstring''' if args.calibrator == "max": __UpperCamelCase = '''max''' elif args.calibrator == "percentile": if args.percentile is None: raise ValueError('''Specify --percentile when using percentile calibrator''' ) __UpperCamelCase = '''histogram''' elif args.calibrator == "mse": __UpperCamelCase = '''histogram''' else: raise ValueError(f"Invalid calibrator {args.calibrator}" ) __UpperCamelCase = QuantDescriptor(num_bits=args.aprec , calib_method=snake_case ) __UpperCamelCase = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)) ) quant_nn.QuantLinear.set_default_quant_desc_input(snake_case ) quant_nn.QuantLinear.set_default_quant_desc_weight(snake_case ) def A_ ( snake_case : Dict , snake_case : str , snake_case : List[str]=False , snake_case : Any=False ) -> Optional[int]: '''simple docstring''' logger.info('''Configuring Model for Quantization''' ) logger.info(f"using quantization package {pytorch_quantization.__file__}" ) if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(snake_case , ['''embeddings'''] , which='''weight''' , _disabled=snake_case ) if args.quant_disable: set_quantizer_by_name(snake_case , [''''''] , _disabled=snake_case ) if args.quant_disable_keyword: set_quantizer_by_name(snake_case , args.quant_disable_keyword , _disabled=snake_case ) if args.quant_disable_layer_module: set_quantizer_by_name(snake_case , [r'''layer.\d+.''' + args.quant_disable_layer_module] , _disabled=snake_case ) if args.quant_enable_layer_module: set_quantizer_by_name(snake_case , [r'''layer.\d+.''' + args.quant_enable_layer_module] , _disabled=snake_case ) if args.recalibrate_weights: recalibrate_weights(snake_case ) if args.fuse_qkv: fuse_qkv(snake_case , snake_case ) if args.clip_gelu: clip_gelu(snake_case , args.clip_gelu ) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(snake_case ) def A_ ( snake_case : str ) -> List[str]: '''simple docstring''' logger.info('''Enabling Calibration''' ) for name, module in model.named_modules(): if name.endswith('''_quantizer''' ): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(f"{name:80}: {module}" ) def A_ ( snake_case : Optional[int] , snake_case : int ) -> List[str]: '''simple docstring''' logger.info('''Loading calibrated amax''' ) for name, module in model.named_modules(): if name.endswith('''_quantizer''' ): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator ): module.load_calib_amax() else: module.load_calib_amax('''percentile''' , percentile=args.percentile ) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(snake_case ) def A_ ( snake_case : Union[str, Any] , snake_case : List[Any] ) -> Any: '''simple docstring''' def fusea(snake_case : Dict , snake_case : Optional[int] , snake_case : Tuple ): for mod in [qq, qk, qv]: if not hasattr(snake_case , '''_amax''' ): print(''' WARNING: NO AMAX BUFFER''' ) return __UpperCamelCase = qq._amax.detach().item() __UpperCamelCase = qk._amax.detach().item() __UpperCamelCase = qv._amax.detach().item() __UpperCamelCase = max(snake_case , snake_case , snake_case ) qq._amax.fill_(snake_case ) qk._amax.fill_(snake_case ) qv._amax.fill_(snake_case ) logger.info(f" q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}" ) for name, mod in model.named_modules(): if name.endswith('''.attention.self''' ): logger.info(f"FUSE_QKV: {name:{name_width}}" ) fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer ) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer ) def A_ ( snake_case : Any , snake_case : int ) -> Optional[Any]: '''simple docstring''' for name, mod in model.named_modules(): if name.endswith('''.output.dense''' ) and not name.endswith('''attention.output.dense''' ): __UpperCamelCase = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=snake_case ) __UpperCamelCase = mod._input_quantizer._amax.data.detach().item() logger.info(f"CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}" ) def A_ ( snake_case : int ) -> Any: '''simple docstring''' for name, mod in model.named_modules(): if hasattr(snake_case , '''_weight_quantizer''' ) and mod._weight_quantizer.axis is not None: __UpperCamelCase = mod.weight.shape[0] __UpperCamelCase = mod._weight_quantizer._amax.detach() __UpperCamelCase = torch.ones(snake_case , dtype=amax.dtype , device=amax.device ) * amax print(f"expanding {name} {amax} -> {mod._weight_quantizer._amax}" ) def A_ ( snake_case : Union[str, Any] ) -> Any: '''simple docstring''' for name, mod in model.named_modules(): if hasattr(snake_case , '''_weight_quantizer''' ): if not hasattr(mod.weight_quantizer , '''_amax''' ): print('''RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER''' ) continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) __UpperCamelCase = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis ) __UpperCamelCase = set(range(len(mod.weight.size() ) ) ) - axis_set __UpperCamelCase = pytorch_quantization.utils.reduce_amax(mod.weight , axis=snake_case , keepdims=snake_case ).detach() logger.info(f"RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}" ) __UpperCamelCase = amax def A_ ( snake_case : str , snake_case : int=25 , snake_case : Optional[int]=180 , snake_case : int=None ) -> List[Any]: '''simple docstring''' if ignore is None: __UpperCamelCase = [] elif not isinstance(snake_case , snake_case ): __UpperCamelCase = [ignore] __UpperCamelCase = 0 for name, mod in model.named_modules(): if not hasattr(snake_case , '''weight''' ): continue __UpperCamelCase = max(snake_case , len(snake_case ) ) for name, mod in model.named_modules(): __UpperCamelCase = getattr(snake_case , '''_input_quantizer''' , snake_case ) __UpperCamelCase = getattr(snake_case , '''_weight_quantizer''' , snake_case ) if not hasattr(snake_case , '''weight''' ): continue if type(snake_case ) in ignore: continue if [True for s in ignore if type(snake_case ) is str and s in name]: continue __UpperCamelCase = f"Act:{input_q.extra_repr()}" __UpperCamelCase = f"Wgt:{weight_q.extra_repr()}" __UpperCamelCase = f"{name:{name_width}} {act_str} {wgt_str}" if len(snake_case ) <= line_width: logger.info(snake_case ) else: logger.info(f"{name:{name_width}} {act_str}" ) logger.info(f"{' ':{name_width}} {wgt_str}" ) def A_ ( snake_case : Dict ) -> List[Any]: '''simple docstring''' __UpperCamelCase = 0 for name, mod in model.named_modules(): if isinstance(snake_case , pytorch_quantization.nn.TensorQuantizer ): print(f"{name:80} {mod}" ) count += 1 print(f"{count} TensorQuantizers found in model" ) def A_ ( snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Optional[Any] , snake_case : str ) -> Dict: '''simple docstring''' __UpperCamelCase = getattr(snake_case , snake_case , snake_case ) if quantizer_mod is not None: assert hasattr(snake_case , snake_case ) setattr(snake_case , snake_case , snake_case ) else: logger.warning(f"{name} has no {quantizer}" ) def A_ ( snake_case : Dict , snake_case : List[Any] , snake_case : Optional[int]="both" , **snake_case : int ) -> int: '''simple docstring''' __UpperCamelCase = f"Warning: changing {which} quantizers of {name:{qname_width}}" for k, v in kwargs.items(): s += f" {k}={v}" if which in ["input", "both"]: set_quantizer(snake_case , snake_case , '''_input_quantizer''' , snake_case , snake_case ) if which in ["weight", "both"]: set_quantizer(snake_case , snake_case , '''_weight_quantizer''' , snake_case , snake_case ) logger.info(snake_case ) def A_ ( snake_case : Dict , snake_case : Union[str, Any] , **snake_case : Tuple ) -> Tuple: '''simple docstring''' for name, mod in model.named_modules(): if hasattr(snake_case , '''_input_quantizer''' ) or hasattr(snake_case , '''_weight_quantizer''' ): for n in names: if re.search(snake_case , snake_case ): set_quantizers(snake_case , snake_case , **snake_case ) elif name.endswith('''_quantizer''' ): for n in names: if re.search(snake_case , snake_case ): __UpperCamelCase = f"Warning: changing {name:{name_width}}" for k, v in kwargs.items(): s += f" {k}={v}" setattr(snake_case , snake_case , snake_case ) logger.info(snake_case )
328
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , **SCREAMING_SNAKE_CASE_ , )-> Optional[int]: '''simple docstring''' super().__init__(features=SCREAMING_SNAKE_CASE_ , cache_dir=SCREAMING_SNAKE_CASE_ , keep_in_memory=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = Sql( cache_dir=SCREAMING_SNAKE_CASE_ , features=SCREAMING_SNAKE_CASE_ , sql=SCREAMING_SNAKE_CASE_ , con=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def A__ ( self )-> Any: '''simple docstring''' __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE_ , download_mode=SCREAMING_SNAKE_CASE_ , verification_mode=SCREAMING_SNAKE_CASE_ , base_path=SCREAMING_SNAKE_CASE_ , ) # Build dataset for splits __UpperCamelCase = self.builder.as_dataset( split='''train''' , verification_mode=SCREAMING_SNAKE_CASE_ , in_memory=self.keep_in_memory ) return dataset class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , )-> List[str]: '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(F"num_proc {num_proc} must be an integer > 0." ) __UpperCamelCase = dataset __UpperCamelCase = name __UpperCamelCase = con __UpperCamelCase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE __UpperCamelCase = num_proc __UpperCamelCase = to_sql_kwargs def A__ ( self )-> int: '''simple docstring''' __UpperCamelCase = self.to_sql_kwargs.pop('''sql''' , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = self.to_sql_kwargs.pop('''con''' , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = self.to_sql_kwargs.pop('''index''' , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = self._write(index=SCREAMING_SNAKE_CASE_ , **self.to_sql_kwargs ) return written def A__ ( self , SCREAMING_SNAKE_CASE_ )-> Dict: '''simple docstring''' __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = args __UpperCamelCase = {**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs __UpperCamelCase = query_table( table=self.dataset.data , key=slice(SCREAMING_SNAKE_CASE_ , offset + self.batch_size ) , indices=self.dataset._indices , ) __UpperCamelCase = batch.to_pandas() __UpperCamelCase = df.to_sql(self.name , self.con , index=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return num_rows or len(SCREAMING_SNAKE_CASE_ ) def A__ ( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )-> int: '''simple docstring''' __UpperCamelCase = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: __UpperCamelCase , __UpperCamelCase = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += num_rows return written
328
1
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = (DEISMultistepScheduler,) snake_case_ = (('num_inference_steps', 25),) def _UpperCamelCase ( self : Optional[int] , **snake_case : List[Any] ): '''simple docstring''' A__ : List[str] = { """num_train_timesteps""": 1000, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """solver_order""": 2, } config.update(**snake_case ) return config def _UpperCamelCase ( self : Optional[Any] , snake_case : Tuple=0 , **snake_case : Any ): '''simple docstring''' A__ : Optional[Any] = dict(self.forward_default_kwargs ) A__ : str = kwargs.pop("""num_inference_steps""" , snake_case ) A__ : Dict = self.dummy_sample A__ : Any = 0.1 * sample A__ : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A__ : int = self.get_scheduler_config(**snake_case ) A__ : Dict = scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # copy over dummy past residuals A__ : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case ) A__ : List[str] = scheduler_class.from_pretrained(snake_case ) new_scheduler.set_timesteps(snake_case ) # copy over dummy past residuals A__ : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A__ , A__ : List[str] = sample, sample for t in range(snake_case , time_step + scheduler.config.solver_order + 1 ): A__ : Union[str, Any] = scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample A__ : Union[str, Any] = new_scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _UpperCamelCase ( self : str ): '''simple docstring''' pass def _UpperCamelCase ( self : Dict , snake_case : Dict=0 , **snake_case : int ): '''simple docstring''' A__ : str = dict(self.forward_default_kwargs ) A__ : Optional[Any] = kwargs.pop("""num_inference_steps""" , snake_case ) A__ : Optional[Any] = self.dummy_sample A__ : str = 0.1 * sample A__ : int = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A__ : List[Any] = self.get_scheduler_config() A__ : Optional[int] = scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # copy over dummy past residuals (must be after setting timesteps) A__ : Tuple = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case ) A__ : Optional[int] = scheduler_class.from_pretrained(snake_case ) # copy over dummy past residuals new_scheduler.set_timesteps(snake_case ) # copy over dummy past residual (must be after setting timesteps) A__ : List[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] A__ : Any = scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample A__ : List[str] = new_scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _UpperCamelCase ( self : Dict , snake_case : Optional[int]=None , **snake_case : Optional[int] ): '''simple docstring''' if scheduler is None: A__ : List[str] = self.scheduler_classes[0] A__ : int = self.get_scheduler_config(**snake_case ) A__ : List[Any] = scheduler_class(**snake_case ) A__ : Optional[int] = self.scheduler_classes[0] A__ : List[Any] = self.get_scheduler_config(**snake_case ) A__ : int = scheduler_class(**snake_case ) A__ : Optional[Any] = 10 A__ : List[Any] = self.dummy_model() A__ : List[Any] = self.dummy_sample_deter scheduler.set_timesteps(snake_case ) for i, t in enumerate(scheduler.timesteps ): A__ : Optional[Any] = model(snake_case , snake_case ) A__ : Any = scheduler.step(snake_case , snake_case , snake_case ).prev_sample return sample def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[int] = dict(self.forward_default_kwargs ) A__ : int = kwargs.pop("""num_inference_steps""" , snake_case ) for scheduler_class in self.scheduler_classes: A__ : int = self.get_scheduler_config() A__ : List[Any] = scheduler_class(**snake_case ) A__ : Optional[Any] = self.dummy_sample A__ : List[str] = 0.1 * sample if num_inference_steps is not None and hasattr(snake_case , """set_timesteps""" ): scheduler.set_timesteps(snake_case ) elif num_inference_steps is not None and not hasattr(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.10] A__ : Tuple = dummy_past_residuals[: scheduler.config.solver_order] A__ : str = scheduler.timesteps[5] A__ : Optional[int] = scheduler.timesteps[6] A__ : Any = scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample A__ : Any = scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Optional[int] = DEISMultistepScheduler(**self.get_scheduler_config() ) A__ : List[str] = self.full_loop(scheduler=snake_case ) A__ : List[str] = torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.23916 ) < 1e-3 A__ : str = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A__ : List[Any] = DPMSolverMultistepScheduler.from_config(scheduler.config ) A__ : Union[str, Any] = UniPCMultistepScheduler.from_config(scheduler.config ) A__ : List[Any] = DEISMultistepScheduler.from_config(scheduler.config ) A__ : List[str] = self.full_loop(scheduler=snake_case ) A__ : List[str] = torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.23916 ) < 1e-3 def _UpperCamelCase ( self : str ): '''simple docstring''' for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' self.check_over_configs(thresholding=snake_case ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=snake_case , prediction_type=snake_case , sample_max_value=snake_case , algorithm_type="""deis""" , solver_order=snake_case , solver_type=snake_case , ) def _UpperCamelCase ( self : str ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=snake_case , solver_type=snake_case , prediction_type=snake_case , algorithm_type=snake_case , ) A__ : Tuple = self.full_loop( solver_order=snake_case , solver_type=snake_case , prediction_type=snake_case , algorithm_type=snake_case , ) assert not torch.isnan(snake_case ).any(), "Samples have nan numbers" def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' self.check_over_configs(lower_order_final=snake_case ) self.check_over_configs(lower_order_final=snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=snake_case , time_step=0 ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = self.full_loop() A__ : Union[str, Any] = torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.23916 ) < 1e-3 def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.full_loop(prediction_type="""v_prediction""" ) A__ : Union[str, Any] = torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.091 ) < 1e-3 def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Tuple = self.scheduler_classes[0] A__ : List[Any] = self.get_scheduler_config(thresholding=snake_case , dynamic_thresholding_ratio=0 ) A__ : Union[str, Any] = scheduler_class(**snake_case ) A__ : List[Any] = 10 A__ : Dict = self.dummy_model() A__ : Optional[Any] = self.dummy_sample_deter.half() scheduler.set_timesteps(snake_case ) for i, t in enumerate(scheduler.timesteps ): A__ : Optional[int] = model(snake_case , snake_case ) A__ : str = scheduler.step(snake_case , snake_case , snake_case ).prev_sample assert sample.dtype == torch.floataa
296
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , snake_case : Tuple , snake_case : List[str]=2 , snake_case : List[str]=8 , snake_case : List[Any]=True , snake_case : Optional[Any]=True , snake_case : List[Any]=True , snake_case : Dict=True , snake_case : Tuple=99 , snake_case : Dict=16 , snake_case : Dict=5 , snake_case : int=2 , snake_case : Any=36 , snake_case : str="gelu" , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : int=512 , snake_case : List[Any]=16 , snake_case : Tuple=2 , snake_case : Any=0.02 , snake_case : Optional[Any]=3 , snake_case : List[Any]=4 , snake_case : str=None , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : Optional[Any] = batch_size A__ : Dict = seq_length A__ : str = is_training A__ : Tuple = use_input_mask A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : int = vocab_size A__ : List[str] = hidden_size A__ : Union[str, Any] = num_hidden_layers A__ : int = num_attention_heads A__ : List[str] = intermediate_size A__ : int = hidden_act A__ : str = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : int = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : int = num_labels A__ : Optional[int] = num_choices A__ : Optional[int] = scope def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Optional[int] = None if self.use_token_type_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : List[str] = None A__ : Union[str, Any] = None if self.use_labels: A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Any = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.get_config() A__ : List[str] = 300 return config def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = self.prepare_config_and_inputs() A__ : List[str] = True A__ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A__ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self : Any , snake_case : Any , snake_case : Tuple , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : List[str] = MraModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) A__ : List[str] = model(snake_case , token_type_ids=snake_case ) A__ : Union[str, Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Dict , snake_case : str , snake_case : Dict , snake_case : str , ): '''simple docstring''' A__ : Dict = True A__ : Optional[Any] = MraModel(snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , ) A__ : Optional[int] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : Dict , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Dict = MraForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , start_positions=snake_case , end_positions=snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _UpperCamelCase ( self : Tuple , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Optional[int] , snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Optional[Any] = MraForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict , snake_case : str , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Union[str, Any] = MraForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : str = MraForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Dict = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = () def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = MraModelTester(self ) A__ : List[str] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[str] = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : str = MraModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason="""MRA does not output attentions""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Any = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : List[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , snake_case ) A__ : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Dict = 5_0265 A__ : List[str] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : List[Any] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) A__ : List[Any] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Union[str, Any] = 5_0265 A__ : Optional[Any] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : Optional[int] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) )
296
1
class lowercase__ : def __init__( self : List[str] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = n SCREAMING_SNAKE_CASE__ = [None] * self.n SCREAMING_SNAKE_CASE__ = 0 # index of the first element SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 def __len__( self : Optional[int] ): return self.size def A_ ( self : Optional[Any] ): return self.size == 0 def A_ ( self : Any ): return False if self.is_empty() else self.array[self.front] def A_ ( self : str , UpperCAmelCase_ : int ): if self.size >= self.n: raise Exception('QUEUE IS FULL' ) SCREAMING_SNAKE_CASE__ = data SCREAMING_SNAKE_CASE__ = (self.rear + 1) % self.n self.size += 1 return self def A_ ( self : Any ): if self.size == 0: raise Exception('UNDERFLOW' ) SCREAMING_SNAKE_CASE__ = self.array[self.front] SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = (self.front + 1) % self.n self.size -= 1 return temp
176
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal __snake_case = logging.get_logger(__name__) __snake_case = TypeVar("""DatasetType""", Dataset, IterableDataset) def _lowercase ( UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = "first_exhausted" , ) -> DatasetType: '''simple docstring''' from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('Unable to interleave an empty list of datasets.' ) for i, dataset in enumerate(UpperCamelCase_ ): if not isinstance(UpperCamelCase_ , (Dataset, IterableDataset) ): if isinstance(UpperCamelCase_ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ' 'is an empty dataset dictionary.' ) raise ValueError( F'Dataset at position {i} has at least one split: {list(UpperCamelCase_ )}\n' F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(UpperCamelCase_ ) )}\']' ) raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(UpperCamelCase_ ).__name__}.' ) if i == 0: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ( (Dataset, IterableDataset) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else (IterableDataset, Dataset) ) elif not isinstance(UpperCamelCase_ , UpperCamelCase_ ): raise ValueError( F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.' ) if dataset_type is Dataset: return _interleave_map_style_datasets( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , info=UpperCamelCase_ , split=UpperCamelCase_ , stopping_strategy=UpperCamelCase_ ) else: return _interleave_iterable_datasets( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , info=UpperCamelCase_ , split=UpperCamelCase_ , stopping_strategy=UpperCamelCase_ ) def _lowercase ( UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = 0 , ) -> DatasetType: '''simple docstring''' if not dsets: raise ValueError('Unable to concatenate an empty list of datasets.' ) for i, dataset in enumerate(UpperCamelCase_ ): if not isinstance(UpperCamelCase_ , (Dataset, IterableDataset) ): if isinstance(UpperCamelCase_ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ' 'is an empty dataset dictionary.' ) raise ValueError( F'Dataset at position {i} has at least one split: {list(UpperCamelCase_ )}\n' F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(UpperCamelCase_ ) )}\']' ) raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(UpperCamelCase_ ).__name__}.' ) if i == 0: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ( (Dataset, IterableDataset) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else (IterableDataset, Dataset) ) elif not isinstance(UpperCamelCase_ , UpperCamelCase_ ): raise ValueError( F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' ) if dataset_type is Dataset: return _concatenate_map_style_datasets(UpperCamelCase_ , info=UpperCamelCase_ , split=UpperCamelCase_ , axis=UpperCamelCase_ ) else: return _concatenate_iterable_datasets(UpperCamelCase_ , info=UpperCamelCase_ , split=UpperCamelCase_ , axis=UpperCamelCase_ )
176
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar __A : Optional[int] = TypeVar("T") class _a ( Generic[T]): """simple docstring""" def __init__( self : Optional[int] , __UpperCamelCase : list[T] , __UpperCamelCase : Callable[[T, T], T] )->None: _UpperCAmelCase = None _UpperCAmelCase = len(__UpperCamelCase ) _UpperCAmelCase = [any_type for _ in range(self.N )] + arr _UpperCAmelCase = fnc self.build() def lowercase__ ( self : int )->None: for p in range(self.N - 1 , 0 , -1 ): _UpperCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def lowercase__ ( self : Any , __UpperCamelCase : int , __UpperCamelCase : T )->None: p += self.N _UpperCAmelCase = v while p > 1: _UpperCAmelCase = p // 2 _UpperCAmelCase = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def lowercase__ ( self : Tuple , __UpperCamelCase : int , __UpperCamelCase : int )->T | None: # noqa: E741 _UpperCAmelCase , _UpperCAmelCase = l + self.N, r + self.N _UpperCAmelCase = None while l <= r: if l % 2 == 1: _UpperCAmelCase = self.st[l] if res is None else self.fn(__UpperCamelCase , self.st[l] ) if r % 2 == 0: _UpperCAmelCase = self.st[r] if res is None else self.fn(__UpperCamelCase , self.st[r] ) _UpperCAmelCase , _UpperCAmelCase = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce __A : int = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] __A : Any = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } __A : Optional[int] = SegmentTree(test_array, min) __A : Union[str, Any] = SegmentTree(test_array, max) __A : List[str] = SegmentTree(test_array, lambda a, b: a + b) def lowercase ( ): '''simple docstring''' for i in range(len(_SCREAMING_SNAKE_CASE ) ): for j in range(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ): _UpperCAmelCase = reduce(_SCREAMING_SNAKE_CASE , test_array[i : j + 1] ) _UpperCAmelCase = reduce(_SCREAMING_SNAKE_CASE , test_array[i : j + 1] ) _UpperCAmelCase = reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert max_range == max_segment_tree.query(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert sum_range == sum_segment_tree.query(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) test_all_segments() for index, value in test_updates.items(): __A : str = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
326
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowercase ( _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' _UpperCAmelCase = int(number**0.5 ) return number == sq * sq def lowercase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' _UpperCAmelCase = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den _UpperCAmelCase = x_den * y_den * z_den _UpperCAmelCase = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowercase ( _SCREAMING_SNAKE_CASE : int = 35 ): '''simple docstring''' _UpperCAmelCase = set() _UpperCAmelCase = 42 _UpperCAmelCase = Fraction(0 ) _UpperCAmelCase = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 _UpperCAmelCase = x_num * y_den + x_den * y_num _UpperCAmelCase = x_den * y_den _UpperCAmelCase = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 _UpperCAmelCase = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) _UpperCAmelCase = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = int(sqrt(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = int(sqrt(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 _UpperCAmelCase = x_num * y_num _UpperCAmelCase = x_den * y_num + x_num * y_den _UpperCAmelCase = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 _UpperCAmelCase = x_num * x_num * y_num * y_num _UpperCAmelCase = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = int(sqrt(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = int(sqrt(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
326
1
def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) UpperCamelCase : Any = (boundary[1] - boundary[0]) / steps UpperCamelCase : List[Any] = boundary[0] UpperCamelCase : List[str] = boundary[1] UpperCamelCase : Tuple = make_points(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Optional[Any] = 0.0 y += (h / 2.0) * f(_lowerCAmelCase ) for i in x_i: # print(i) y += h * f(_lowerCAmelCase ) y += (h / 2.0) * f(_lowerCAmelCase ) return y def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Tuple: UpperCamelCase : int = a + h while x < (b - h): yield x UpperCamelCase : Any = x + h def A_ ( _lowerCAmelCase ) -> Optional[Any]: # enter your function here UpperCamelCase : Union[str, Any] = (x - 0) * (x - 0) return y def A_ ( ) -> Dict: UpperCamelCase : Optional[int] = 0.0 # Lower bound of integration UpperCamelCase : Dict = 1.0 # Upper bound of integration UpperCamelCase : Optional[int] = 10.0 # define number of steps or resolution UpperCamelCase : Optional[int] = [a, b] # define boundary of integration UpperCamelCase : int = method_a(_lowerCAmelCase , _lowerCAmelCase ) print(F"""y = {y}""" ) if __name__ == "__main__": main()
52
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a__ ( A__ ): def __init__( self : Tuple,_A : Optional[int],_A : Any=13,_A : List[str]=7,_A : int=True,_A : Dict=True,_A : Dict=False,_A : List[Any]=True,_A : Any=99,_A : Optional[int]=32,_A : Any=5,_A : List[Any]=4,_A : Dict=64,_A : Optional[Any]="gelu",_A : Tuple=0.1,_A : Any=0.1,_A : List[Any]=512,_A : Dict=16,_A : Optional[Any]=2,_A : Union[str, Any]=0.02,_A : List[str]=3,_A : Optional[Any]=4,_A : Union[str, Any]=None,_A : Tuple=2,_A : List[str]=2,_A : str=2,_A : Dict=2,_A : Optional[Any]=4,_A : Union[str, Any]=1,): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = seq_length SCREAMING_SNAKE_CASE_ : Dict = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : int = use_token_type_ids SCREAMING_SNAKE_CASE_ : Optional[int] = use_labels SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = max_position_embeddings SCREAMING_SNAKE_CASE_ : str = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE_ : Tuple = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = num_choices SCREAMING_SNAKE_CASE_ : Dict = scope SCREAMING_SNAKE_CASE_ : int = q_groups SCREAMING_SNAKE_CASE_ : Tuple = k_groups SCREAMING_SNAKE_CASE_ : List[Any] = v_groups SCREAMING_SNAKE_CASE_ : Tuple = post_attention_groups SCREAMING_SNAKE_CASE_ : int = intermediate_groups SCREAMING_SNAKE_CASE_ : List[Any] = output_groups def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length],self.vocab_size ) SCREAMING_SNAKE_CASE_ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : str = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size],self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length],self.num_labels ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size],self.num_choices ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : str ): """simple docstring""" return SqueezeBertConfig( embedding_size=self.hidden_size,vocab_size=self.vocab_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,attention_probs_dropout_prob=self.hidden_dropout_prob,attention_dropout=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,initializer_range=self.initializer_range,q_groups=self.q_groups,k_groups=self.k_groups,v_groups=self.v_groups,post_attention_groups=self.post_attention_groups,intermediate_groups=self.intermediate_groups,output_groups=self.output_groups,) def __UpperCamelCase ( self : Tuple,_A : Union[str, Any],_A : Union[str, Any],_A : int,_A : Optional[int],_A : Union[str, Any],_A : Any ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = SqueezeBertModel(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE_ : Any = model(_A,_A ) SCREAMING_SNAKE_CASE_ : List[str] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self : Dict,_A : Any,_A : Tuple,_A : str,_A : Any,_A : Union[str, Any],_A : Any ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = SqueezeBertForMaskedLM(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE_ : List[str] = model(_A,attention_mask=_A,labels=_A ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : Optional[int],_A : Union[str, Any],_A : Union[str, Any],_A : Any,_A : Tuple,_A : int,_A : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = SqueezeBertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE_ : Dict = model( _A,attention_mask=_A,start_positions=_A,end_positions=_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 : List[Any],_A : List[str],_A : Tuple,_A : List[Any],_A : List[str],_A : List[str],_A : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.num_labels SCREAMING_SNAKE_CASE_ : List[str] = SqueezeBertForSequenceClassification(_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE_ : Dict = model(_A,attention_mask=_A,labels=_A ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels) ) def __UpperCamelCase ( self : str,_A : Optional[int],_A : str,_A : List[Any],_A : List[str],_A : str,_A : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = SqueezeBertForTokenClassification(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model(_A,attention_mask=_A,labels=_A ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : List[Any],_A : Tuple,_A : str,_A : Optional[Any],_A : int,_A : str,_A : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = SqueezeBertForMultipleChoice(config=_A ) model.to(_A ) model.eval() SCREAMING_SNAKE_CASE_ : Dict = input_ids.unsqueeze(1 ).expand(-1,self.num_choices,-1 ).contiguous() SCREAMING_SNAKE_CASE_ : str = input_mask.unsqueeze(1 ).expand(-1,self.num_choices,-1 ).contiguous() SCREAMING_SNAKE_CASE_ : Optional[int] = model( _A,attention_mask=_A,labels=_A,) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : Dict = config_and_inputs SCREAMING_SNAKE_CASE_ : Dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class a__ ( A__ , A__ , unittest.TestCase ): A = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) A = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) A = False A = True A = False def __UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE_ : List[str] = ConfigTester(self,config_class=_A,dim=37 ) def __UpperCamelCase ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*_A ) def __UpperCamelCase ( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*_A ) def __UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*_A ) def __UpperCamelCase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*_A ) def __UpperCamelCase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*_A ) def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*_A ) @slow def __UpperCamelCase ( self : Any ): """simple docstring""" for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Tuple = SqueezeBertModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_sentencepiece @require_tokenizers @require_torch class a__ ( unittest.TestCase ): @slow def __UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli" ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE_ : List[Any] = model(_A )[0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.Size((1, 3) ) self.assertEqual(output.shape,_A ) SCREAMING_SNAKE_CASE_ : int = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(_A,_A,atol=1E-4 ) )
18
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=lowercase_ ): lowerCAmelCase_ : Optional[int] = ["keras_nlp"] def __init__( self , *a__ , **a__ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ["keras_nlp"] )
358
'''simple docstring''' def UpperCamelCase_( snake_case : int = 1_0_0_0 ): '''simple docstring''' snake_case_ = 3 snake_case_ = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 1_5 == 0: result -= a a += 1 return result if __name__ == "__main__": print(F"{solution() = }")
92
0
"""simple docstring""" from __future__ import annotations def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
100
"""simple docstring""" from __future__ import annotations __magic_name__ = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __magic_name__ = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) for i in range(UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = -1 for j in range(i + 1 , UpperCamelCase_ ): if arr[i] < arr[j]: __SCREAMING_SNAKE_CASE = arr[j] break result.append(UpperCamelCase_ ) return result def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [] for i, outer in enumerate(UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = -1 for inner in arr[i + 1 :]: if outer < inner: __SCREAMING_SNAKE_CASE = inner break result.append(UpperCamelCase_ ) return result def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [-1] * arr_size for index in reversed(range(UpperCamelCase_ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: __SCREAMING_SNAKE_CASE = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) __magic_name__ = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
100
1
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig 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_config_docstrings.py lowercase : Tuple = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowercase : str = direct_transformers_import(PATH_TO_TRANSFORMERS) lowercase : Any = transformers.models.auto.configuration_auto.CONFIG_MAPPING lowercase : str = { # used to compute the property `self.chunk_length` '''EncodecConfig''': ['''overlap'''], # used as `self.bert_model = BertModel(config, ...)` '''DPRConfig''': True, # not used in modeling files, but it's an important information '''FSMTConfig''': ['''langs'''], # used internally in the configuration class file '''GPTNeoConfig''': ['''attention_types'''], # used internally in the configuration class file '''EsmConfig''': ['''is_folding_model'''], # used during training (despite we don't have training script for these models yet) '''Mask2FormerConfig''': ['''ignore_value'''], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) '''OneFormerConfig''': ['''ignore_value''', '''norm'''], # used during preprocessing and collation, see `collating_graphormer.py` '''GraphormerConfig''': ['''spatial_pos_max'''], # used internally in the configuration class file '''T5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally '''MT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], '''UMT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], # used internally in the configuration class file '''LongT5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file '''SwitchTransformersConfig''': ['''feed_forward_proj'''], # having default values other than `1e-5` - we can't fix them without breaking '''BioGptConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''GLPNConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''SegformerConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''CvtConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''PerceiverConfig''': ['''layer_norm_eps'''], # used internally to calculate the feature size '''InformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''TimeSeriesTransformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''AutoformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate `mlp_dim` '''SamVisionConfig''': ['''mlp_ratio'''], # For (head) training, but so far not implemented '''ClapAudioConfig''': ['''num_classes'''], # Not used, but providing useful information to users '''SpeechT5HifiGanConfig''': ['''sampling_rate'''], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { 'CLIPSegConfig': True, 'DeformableDetrConfig': True, 'DetaConfig': True, 'DinatConfig': True, 'DonutSwinConfig': True, 'EfficientFormerConfig': True, 'FSMTConfig': True, 'JukeboxConfig': True, 'LayoutLMv2Config': True, 'MaskFormerSwinConfig': True, 'MT5Config': True, 'NatConfig': True, 'OneFormerConfig': True, 'PerceiverConfig': True, 'RagConfig': True, 'SpeechT5Config': True, 'SwinConfig': True, 'Swin2SRConfig': True, 'Swinv2Config': True, 'SwitchTransformersConfig': True, 'TableTransformerConfig': True, 'TapasConfig': True, 'TransfoXLConfig': True, 'UniSpeechConfig': True, 'UniSpeechSatConfig': True, 'WavLMConfig': True, 'WhisperConfig': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) 'JukeboxPriorConfig': True, # TODO: @Younes (for `is_decoder`) 'Pix2StructTextConfig': True, } ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F'config.{attribute}' in modeling_source or F'getattr(config, "{attribute}"' in modeling_source or F'getattr(self.config, "{attribute}"' in modeling_source ): A : Tuple = True # Deal with multi-line cases elif ( re.search( RF'getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"' , _a , ) is not None ): A : str = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: A : str = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files A : List[Any] = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] A : List[str] = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed A : Optional[Any] = True if not attribute_used: A : Any = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: A : Tuple = True elif attribute in ["tie_word_embeddings"] and default_value is False: A : Dict = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: A : Union[str, Any] = True elif attribute.endswith('''_token_id''' ): A : Dict = True # configuration class specific cases if not case_allowed: A : Any = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) A : int = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : str = dict(inspect.signature(config_class.__init__ ).parameters ) A : Optional[Any] = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] A : Optional[Any] = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass A : Union[str, Any] = {} if len(config_class.attribute_map ) > 0: A : Union[str, Any] = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files A : Union[str, Any] = inspect.getsourcefile(_a ) A : Optional[int] = os.path.dirname(_a ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. A : Optional[int] = [os.path.join(_a , _a ) for fn in os.listdir(_a ) if fn.startswith('''modeling_''' )] # Get the source code strings A : Tuple = [] for path in modeling_paths: if os.path.isfile(_a ): with open(_a ) as fp: modeling_sources.append(fp.read() ) A : str = [] for config_param, default_value in zip(_a , _a ): # `attributes` here is all the variant names for `config_param` A : List[str] = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(_a , _a , _a , _a ): unused_attributes.append(attributes[0] ) return sorted(_a ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) A : str = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda snake_case__ : inspect.isclass(_a ) and issubclass(_a , _a ) and inspect.getmodule(_a ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: A : int = check_config_attributes_being_used(_a ) if len(_a ) > 0: A : Tuple = unused_attributes if len(_a ) > 0: A : Optional[Any] = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += F'{name}: {attributes}\n' raise ValueError(_a ) if __name__ == "__main__": check_config_attributes()
364
'''simple docstring''' from __future__ import annotations lowercase : Union[str, Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] lowercase : Any = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" A : int = pos_x A : Optional[Any] = pos_y A : Optional[Any] = (pos_y, pos_x) A : str = goal_x A : Optional[int] = goal_y A : List[Any] = g_cost A : str = parent A : str = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : Optional[int] = abs(self.pos_x - self.goal_x ) A : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : Optional[Any] = [self.start] A : list[Node] = [] A : Tuple = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : Optional[int] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Any = self.get_successors(SCREAMING_SNAKE_CASE ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : List[Any] = [] for action in delta: A : List[str] = parent.pos_x + action[1] A : Dict = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : int = node A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : int = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : List[str] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : int = GreedyBestFirst(init, goal) lowercase : Union[str, Any] = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Dict = 2 for elem in grid: print(elem)
311
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : str = logging.get_logger(__name__) lowerCamelCase_ : str = { """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 __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "pegasus" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , __A=5_0265 , __A=1024 , __A=12 , __A=4096 , __A=16 , __A=12 , __A=4096 , __A=16 , __A=0.0 , __A=0.0 , __A=True , __A=True , __A="gelu" , __A=1024 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=0 , __A=False , __A=0 , __A=1 , __A=1 , **__A , ) -> Union[str, Any]: a =vocab_size a =max_position_embeddings a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =encoder_layerdrop a =decoder_layerdrop a =use_cache a =encoder_layers a =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=__A , eos_token_id=__A , is_encoder_decoder=__A , decoder_start_token_id=__A , forced_eos_token_id=__A , **__A , ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model
81
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(vocab=__A , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> str: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class a_ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : str , lowercase__ : pyspark.sql.DataFrame , lowercase__ : Optional[NamedSplit] = None , lowercase__ : Optional[Features] = None , lowercase__ : bool = True , lowercase__ : str = None , lowercase__ : bool = False , lowercase__ : str = None , lowercase__ : bool = True , lowercase__ : str = "arrow" , **lowercase__ : Any , ): '''simple docstring''' super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) lowerCAmelCase__ = load_from_cache_file lowerCAmelCase__ = file_format lowerCAmelCase__ = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __snake_case ( self : Tuple): '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split) lowerCAmelCase__ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split)
361
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def __lowerCamelCase ( lowerCAmelCase__ ): lowerCAmelCase__ = 'huggingface/label-files' lowerCAmelCase__ = 'imagenet-1k-id2label.json' lowerCAmelCase__ = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='dataset' ) , 'r' ) ) lowerCAmelCase__ = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} lowerCAmelCase__ = {v: k for k, v in idalabel.items()} lowerCAmelCase__ = 'std_conv' if 'bit' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" lowerCAmelCase__ = BitConfig( conv_layer=lowerCAmelCase__ , num_labels=1_0_0_0 , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , ) return config def __lowerCamelCase ( lowerCAmelCase__ ): if "stem.conv" in name: lowerCAmelCase__ = name.replace('stem.conv' , 'bit.embedder.convolution' ) if "blocks" in name: lowerCAmelCase__ = name.replace('blocks' , 'layers' ) if "head.fc" in name: lowerCAmelCase__ = name.replace('head.fc' , 'classifier.1' ) if name.startswith('norm' ): lowerCAmelCase__ = 'bit.' + name if "bit" not in name and "classifier" not in name: lowerCAmelCase__ = 'bit.encoder.' + name return name def __lowerCamelCase ( ): lowerCAmelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' lowerCAmelCase__ = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ): lowerCAmelCase__ = get_config(lowerCAmelCase__ ) # load original model from timm lowerCAmelCase__ = create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ) timm_model.eval() # load state_dict of original model lowerCAmelCase__ = timm_model.state_dict() for key in state_dict.copy().keys(): lowerCAmelCase__ = state_dict.pop(lowerCAmelCase__ ) lowerCAmelCase__ = val.squeeze() if 'head' in key else val # load HuggingFace model lowerCAmelCase__ = BitForImageClassification(lowerCAmelCase__ ) model.eval() model.load_state_dict(lowerCAmelCase__ ) # create image processor lowerCAmelCase__ = create_transform(**resolve_data_config({} , model=lowerCAmelCase__ ) ) lowerCAmelCase__ = transform.transforms lowerCAmelCase__ = { 'bilinear': PILImageResampling.BILINEAR, 'bicubic': PILImageResampling.BICUBIC, 'nearest': PILImageResampling.NEAREST, } lowerCAmelCase__ = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'shortest_edge': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowerCAmelCase__ , crop_size={'height': timm_transforms[1].size[0], 'width': timm_transforms[1].size[1]} , do_normalize=lowerCAmelCase__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = transform(lowerCAmelCase__ ).unsqueeze(0 ) lowerCAmelCase__ = processor(lowerCAmelCase__ , return_tensors='pt' ).pixel_values # verify pixel values assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ) # verify logits with torch.no_grad(): lowerCAmelCase__ = model(lowerCAmelCase__ ) lowerCAmelCase__ = outputs.logits print('Logits:' , logits[0, :3] ) print('Predicted class:' , model.config.idalabel[logits.argmax(-1 ).item()] ) lowerCAmelCase__ = timm_model(lowerCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase__ , outputs.logits , atol=1e-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) print(F"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(F"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(F"""ybelkada/{model_name}""" ) processor.push_to_hub(F"""ybelkada/{model_name}""" ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
119
0
"""simple docstring""" from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min_version, require_tpu, require_xpu, skip, slow, ) from .training import RegressionDataset, RegressionModel, RegressionModelaXPU from .scripts import test_script, test_sync, test_ops # isort: skip
160
'''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 UpperCamelCase__ ( lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxAutoencoderKL @property def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = 4 SCREAMING_SNAKE_CASE : str = 3 SCREAMING_SNAKE_CASE : List[Any] = (32, 32) SCREAMING_SNAKE_CASE : Tuple = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE : Any = jax.random.uniform(lowerCamelCase_ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } SCREAMING_SNAKE_CASE : List[Any] = self.dummy_input return init_dict, inputs_dict
323
0
'''simple docstring''' import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class UpperCAmelCase_ ( snake_case__ ): '''simple docstring''' def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(_A , """neck_hidden_sizes""" ) ) self.parent.assertTrue(hasattr(_A , """num_attention_heads""" ) ) class UpperCAmelCase_ : '''simple docstring''' def __init__( self , _lowercase , _lowercase=13 , _lowercase=32 , _lowercase=2 , _lowercase=3 , _lowercase=640 , _lowercase=4 , _lowercase="silu" , _lowercase=3 , _lowercase=32 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.1 , _lowercase=0.02 , _lowercase=True , _lowercase=True , _lowercase=10 , _lowercase=None , ): """simple docstring""" _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = num_channels _lowerCAmelCase = last_hidden_size _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_act _lowerCAmelCase = conv_kernel_size _lowerCAmelCase = output_stride _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = classifier_dropout_prob _lowerCAmelCase = use_labels _lowerCAmelCase = is_training _lowerCAmelCase = num_labels _lowerCAmelCase = initializer_range _lowerCAmelCase = scope def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase = None _lowerCAmelCase = None if self.use_labels: _lowerCAmelCase = ids_tensor([self.batch_size] , self.num_labels ) _lowerCAmelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) _lowerCAmelCase = self.get_config() return config, pixel_values, labels, pixel_labels def _lowercase ( self ): """simple docstring""" return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = MobileViTModel(config=_A ) model.to(_A ) model.eval() _lowerCAmelCase = model(_A ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = self.num_labels _lowerCAmelCase = MobileViTForImageClassification(_A ) model.to(_A ) model.eval() _lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" _lowerCAmelCase = self.num_labels _lowerCAmelCase = MobileViTForSemanticSegmentation(_A ) model.to(_A ) model.eval() _lowerCAmelCase = model(_A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = config_and_inputs _lowerCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' _lowercase : Any = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) _lowercase : Union[str, Any] = ( { """feature-extraction""": MobileViTModel, """image-classification""": MobileViTForImageClassification, """image-segmentation""": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) _lowercase : int = False _lowercase : Union[str, Any] = False _lowercase : List[str] = False _lowercase : Dict = False def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = MobileViTModelTester(self ) _lowerCAmelCase = MobileViTConfigTester(self , config_class=_A , has_text_modality=_A ) def _lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViT does not use inputs_embeds""" ) def _lowercase ( self ): """simple docstring""" pass @unittest.skip(reason="""MobileViT does not support input and output embeddings""" ) def _lowercase ( self ): """simple docstring""" pass @unittest.skip(reason="""MobileViT does not output attentions""" ) def _lowercase ( self ): """simple docstring""" pass def _lowercase ( self ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = model_class(_A ) _lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase = [*signature.parameters.keys()] _lowerCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _A ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _lowercase ( self ): """simple docstring""" pass def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def _lowercase ( self ): """simple docstring""" def check_hidden_states_output(_lowercase , _lowercase , _lowercase ): _lowerCAmelCase = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): _lowerCAmelCase = model(**self._prepare_for_class(_A , _A ) ) _lowerCAmelCase = outputs.hidden_states _lowerCAmelCase = 5 self.assertEqual(len(_A ) , _A ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. _lowerCAmelCase = 2 for i in range(len(_A ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase = True check_hidden_states_output(_A , _A , _A ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_A ) @slow def _lowercase ( self ): """simple docstring""" for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase = MobileViTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def A (): _lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _lowercase ( self ): """simple docstring""" return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""" ) if is_vision_available() else None @slow def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""" ).to(_A ) _lowerCAmelCase = self.default_image_processor _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(images=_A , return_tensors="""pt""" ).to(_A ) # forward pass with torch.no_grad(): _lowerCAmelCase = model(**_A ) # verify the logits _lowerCAmelCase = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _A ) _lowerCAmelCase = torch.tensor([-1.9364, -1.2327, -0.4653] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1e-4 ) ) @slow def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) _lowerCAmelCase = model.to(_A ) _lowerCAmelCase = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(images=_A , return_tensors="""pt""" ).to(_A ) # forward pass with torch.no_grad(): _lowerCAmelCase = model(**_A ) _lowerCAmelCase = outputs.logits # verify the logits _lowerCAmelCase = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _A ) _lowerCAmelCase = torch.tensor( [ [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]], [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]], ] , device=_A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _A , atol=1e-4 ) ) @slow def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) _lowerCAmelCase = model.to(_A ) _lowerCAmelCase = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(images=_A , return_tensors="""pt""" ).to(_A ) # forward pass with torch.no_grad(): _lowerCAmelCase = model(**_A ) _lowerCAmelCase = outputs.logits.detach().cpu() _lowerCAmelCase = image_processor.post_process_semantic_segmentation(outputs=_A , target_sizes=[(50, 60)] ) _lowerCAmelCase = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _A ) _lowerCAmelCase = image_processor.post_process_semantic_segmentation(outputs=_A ) _lowerCAmelCase = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _A )
364
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _lowercase , _lowercase ): """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM _lowerCAmelCase = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_lowercase , scheduler=_lowercase ) @torch.no_grad() def __call__( self , _lowercase = 1 , _lowercase = None , _lowercase = 0.0 , _lowercase = 50 , _lowercase = None , _lowercase = "pil" , _lowercase = True , ): """simple docstring""" if isinstance(self.unet.config.sample_size , _lowercase ): _lowerCAmelCase = ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: _lowerCAmelCase = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(_lowercase , _lowercase ) and len(_lowercase ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(_lowercase )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) _lowerCAmelCase = randn_tensor(_lowercase , generator=_lowercase , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_lowercase ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _lowerCAmelCase = self.unet(_lowercase , _lowercase ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _lowerCAmelCase = self.scheduler.step( _lowercase , _lowercase , _lowercase , eta=_lowercase , use_clipped_model_output=_lowercase , generator=_lowercase ).prev_sample _lowerCAmelCase = (image / 2 + 0.5).clamp(0 , 1 ) _lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _lowerCAmelCase = self.numpy_to_pil(_lowercase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowercase )
229
0
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler A__ = 16 A__ = 32 def _UpperCAmelCase ( snake_case , snake_case = 16 , snake_case = "bert-base-cased" ): """simple docstring""" _lowerCAmelCase = AutoTokenizer.from_pretrained(snake_case ) _lowerCAmelCase = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case ): # max_length=None => use the model max length (it's actually the default) _lowerCAmelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case , max_length=snake_case ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset _lowerCAmelCase = datasets.map( snake_case , batched=snake_case , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=snake_case ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowerCAmelCase = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(snake_case , padding="""max_length""" , max_length=1_28 , return_tensors="""pt""" ) return tokenizer.pad(snake_case , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. _lowerCAmelCase = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case , collate_fn=snake_case , batch_size=snake_case ) _lowerCAmelCase = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case , collate_fn=snake_case , batch_size=snake_case ) return train_dataloader, eval_dataloader def _UpperCAmelCase ( snake_case , snake_case , snake_case , snake_case ): """simple docstring""" model.eval() _lowerCAmelCase = 0 for step, batch in enumerate(snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCAmelCase = model(**snake_case ) _lowerCAmelCase = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _lowerCAmelCase , _lowerCAmelCase = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(snake_case ) - 1: _lowerCAmelCase = predictions[: len(eval_dataloader.dataset ) - samples_seen] _lowerCAmelCase = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=snake_case , references=snake_case , ) _lowerCAmelCase = metric.compute() return eval_metric["accuracy"] def _UpperCAmelCase ( snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowerCAmelCase = config["""lr"""] _lowerCAmelCase = int(config["""num_epochs"""] ) _lowerCAmelCase = int(config["""seed"""] ) _lowerCAmelCase = int(config["""batch_size"""] ) _lowerCAmelCase = args.model_name_or_path set_seed(snake_case ) _lowerCAmelCase , _lowerCAmelCase = get_dataloaders(snake_case , snake_case , snake_case ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowerCAmelCase = AutoModelForSequenceClassification.from_pretrained(snake_case , return_dict=snake_case ) # Instantiate optimizer _lowerCAmelCase = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _lowerCAmelCase = optimizer_cls(params=model.parameters() , lr=snake_case ) if accelerator.state.deepspeed_plugin is not None: _lowerCAmelCase = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: _lowerCAmelCase = 1 _lowerCAmelCase = (len(snake_case ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _lowerCAmelCase = get_linear_schedule_with_warmup( optimizer=snake_case , num_warmup_steps=0 , num_training_steps=snake_case , ) else: _lowerCAmelCase = DummyScheduler(snake_case , total_num_steps=snake_case , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = accelerator.prepare( snake_case , snake_case , snake_case , snake_case , snake_case ) # We need to keep track of how many total steps we have iterated over _lowerCAmelCase = 0 # We also need to keep track of the stating epoch so files are named properly _lowerCAmelCase = 0 _lowerCAmelCase = evaluate.load("""glue""" , """mrpc""" ) _lowerCAmelCase = num_epochs if args.partial_train_epoch is not None: _lowerCAmelCase = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) _lowerCAmelCase = args.resume_from_checkpoint.split("""epoch_""" )[1] _lowerCAmelCase = """""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break _lowerCAmelCase = int(snake_case ) + 1 _lowerCAmelCase = evaluation_loop(snake_case , snake_case , snake_case , snake_case ) accelerator.print("""resumed checkpoint performance:""" , snake_case ) accelerator.print("""resumed checkpoint's scheduler's lr:""" , lr_scheduler.get_lr()[0] ) accelerator.print("""resumed optimizers's lr:""" , optimizer.param_groups[0]["""lr"""] ) with open(os.path.join(args.output_dir , F'state_{starting_epoch-1}.json' ) , """r""" ) as f: _lowerCAmelCase = json.load(snake_case ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model _lowerCAmelCase = {} for epoch in range(snake_case , snake_case ): model.train() for step, batch in enumerate(snake_case ): _lowerCAmelCase = model(**snake_case ) _lowerCAmelCase = outputs.loss _lowerCAmelCase = loss / gradient_accumulation_steps accelerator.backward(snake_case ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 _lowerCAmelCase = F'epoch_{epoch}' _lowerCAmelCase = os.path.join(args.output_dir , snake_case ) accelerator.save_state(snake_case ) _lowerCAmelCase = evaluation_loop(snake_case , snake_case , snake_case , snake_case ) _lowerCAmelCase = accuracy _lowerCAmelCase = lr_scheduler.get_lr()[0] _lowerCAmelCase = optimizer.param_groups[0]["""lr"""] _lowerCAmelCase = epoch _lowerCAmelCase = overall_step accelerator.print(F'epoch {epoch}:' , snake_case ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , F'state_{epoch}.json' ) , """w""" ) as f: json.dump(snake_case , snake_case ) def _UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=snake_case , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=snake_case , ) parser.add_argument( """--output_dir""" , type=snake_case , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=snake_case , default=snake_case , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--partial_train_epoch""" , type=snake_case , default=snake_case , help="""If passed, the training will stop after this number of epochs.""" , ) parser.add_argument( """--num_epochs""" , type=snake_case , default=2 , help="""Number of train epochs.""" , ) _lowerCAmelCase = parser.parse_args() _lowerCAmelCase = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(snake_case , snake_case ) if __name__ == "__main__": main()
82
"""simple docstring""" import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class _UpperCAmelCase : UpperCamelCase = None def lowerCamelCase ( self :List[Any] ): A = self.feature_extraction_class(**self.feat_extract_dict ) A = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __UpperCamelCase ) def lowerCamelCase ( self :Dict ): A = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = os.path.join(__UpperCamelCase , "feat_extract.json" ) feat_extract_first.to_json_file(__UpperCamelCase ) A = self.feature_extraction_class.from_json_file(__UpperCamelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase ( self :Dict ): A = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A = feat_extract_first.save_pretrained(__UpperCamelCase )[0] check_json_file_has_correct_format(__UpperCamelCase ) A = self.feature_extraction_class.from_pretrained(__UpperCamelCase ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase ( self :Tuple ): A = self.feature_extraction_class() self.assertIsNotNone(__UpperCamelCase )
292
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class a_ ( a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = StableDiffusionPanoramaPipeline __SCREAMING_SNAKE_CASE : List[Any] = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS __SCREAMING_SNAKE_CASE : str = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE : Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS def __lowerCAmelCase ( self ) ->Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler() torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Tuple = CLIPTextModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE : List[str] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->List[str]: SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, # Setting height and width to None to prevent OOMs on CPU. '''height''': None, '''width''': None, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[str] = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self ) ->Tuple: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 ) def __lowerCAmelCase ( self ) ->int: SCREAMING_SNAKE_CASE : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = '''french fries''' SCREAMING_SNAKE_CASE : int = sd_pipe(**_lowerCamelCase , negative_prompt=_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : str = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(**_lowerCamelCase , view_batch_size=2 ) SCREAMING_SNAKE_CASE : Optional[int] = output.images SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : int = self.get_dummy_components() SCREAMING_SNAKE_CASE : int = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' ) SCREAMING_SNAKE_CASE : int = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , skip_prk_steps=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPanoramaPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self , _lowerCamelCase=0 ) ->Tuple: SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : List[str] = '''stabilityai/stable-diffusion-2-base''' SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) SCREAMING_SNAKE_CASE : Any = StableDiffusionPanoramaPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : List[str] = self.get_inputs() SCREAMING_SNAKE_CASE : Any = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) SCREAMING_SNAKE_CASE : List[str] = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[int] = StableDiffusionPanoramaPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-base''' , safety_checker=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : str = self.get_inputs() SCREAMING_SNAKE_CASE : List[Any] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) SCREAMING_SNAKE_CASE : List[str] = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : Optional[int] = 0 def callback_fn(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> None: SCREAMING_SNAKE_CASE : str = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE : Dict = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) SCREAMING_SNAKE_CASE : int = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Optional[int] = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) SCREAMING_SNAKE_CASE : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE : Optional[int] = False SCREAMING_SNAKE_CASE : Tuple = '''stabilityai/stable-diffusion-2-base''' SCREAMING_SNAKE_CASE : str = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE : int = self.get_inputs() pipe(**_lowerCamelCase , callback=_lowerCamelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowerCAmelCase ( self ) ->Dict: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE : Tuple = '''stabilityai/stable-diffusion-2-base''' SCREAMING_SNAKE_CASE : List[str] = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) SCREAMING_SNAKE_CASE : int = StableDiffusionPanoramaPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE : int = self.get_inputs() SCREAMING_SNAKE_CASE : Tuple = pipe(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXGLMForCausalLM''', '''TFXGLMModel''', '''TFXGLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
1
"""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 import BertTokenizer _a : int= logging.get_logger(__name__) _a : List[Any]= {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _a : Optional[Any]= { "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" ), }, } _a : Union[str, Any]= { "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" ), }, } _a : Optional[int]= { "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" ), }, } _a : Union[str, Any]= { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } _a : int= { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } _a : List[str]= { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } _a : int= { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _a : List[str]= { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _a : int= { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class UpperCamelCase ( __lowerCAmelCase ): UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCAmelCase : Any = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Tuple = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : Optional[int] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class UpperCamelCase ( __lowerCAmelCase ): UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES UpperCAmelCase : Dict = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Dict = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _a : Dict= collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) _a : Union[str, Any]= collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) _a : str= R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n ```\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n ```\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Returns:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(__lowerCAmelCase ) class UpperCamelCase : def __call__(self : Dict , _A : List[Any] , _A : Optional[str] = None , _A : Optional[str] = None , _A : Union[bool, str] = False , _A : Union[bool, str] = False , _A : Optional[int] = None , _A : Optional[Union[str, TensorType]] = None , _A : Optional[bool] = None , **_A : List[str] , ) -> Dict: if titles is None and texts is None: return super().__call__( lowerCamelCase_ , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=lowerCamelCase_ , return_tensors=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , **lowerCamelCase_ , ) elif titles is None or texts is None: __snake_case : str = titles if texts is None else texts return super().__call__( lowerCamelCase_ , lowerCamelCase_ , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=lowerCamelCase_ , return_tensors=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , **lowerCamelCase_ , ) __snake_case : Union[str, Any] = titles if not isinstance(lowerCamelCase_ , lowerCamelCase_) else [titles] __snake_case : Any = texts if not isinstance(lowerCamelCase_ , lowerCamelCase_) else [texts] __snake_case : Union[str, Any] = len(lowerCamelCase_) __snake_case : Optional[int] = questions if not isinstance(lowerCamelCase_ , lowerCamelCase_) else [questions] * n_passages if len(lowerCamelCase_) != len(lowerCamelCase_): raise ValueError( f"There should be as many titles than texts but got {len(lowerCamelCase_)} titles and {len(lowerCamelCase_)} texts.") __snake_case : Optional[Any] = super().__call__(lowerCamelCase_ , lowerCamelCase_ , padding=lowerCamelCase_ , truncation=lowerCamelCase_)['input_ids'] __snake_case : str = super().__call__(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , padding=lowerCamelCase_ , truncation=lowerCamelCase_)['input_ids'] __snake_case : Optional[Any] = { 'input_ids': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowerCamelCase_ , lowerCamelCase_) ] } if return_attention_mask is not False: __snake_case : Optional[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]) __snake_case : Any = attention_mask return self.pad(lowerCamelCase_ , padding=lowerCamelCase_ , max_length=lowerCamelCase_ , return_tensors=lowerCamelCase_) def _lowercase (self : str , _A : BatchEncoding , _A : DPRReaderOutput , _A : int = 16 , _A : int = 64 , _A : int = 4 , ) -> Union[str, Any]: __snake_case : Optional[int] = reader_input['input_ids'] __snake_case , __snake_case , __snake_case : Optional[Any] = reader_output[:3] __snake_case : Tuple = len(lowerCamelCase_) __snake_case : Dict = sorted(range(lowerCamelCase_) , reverse=lowerCamelCase_ , key=relevance_logits.__getitem__) __snake_case : str = [] for doc_id in sorted_docs: __snake_case : Tuple = list(input_ids[doc_id]) # assuming question & title information is at the beginning of the sequence __snake_case : List[str] = sequence_ids.index(self.sep_token_id , 2) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __snake_case : Optional[Any] = sequence_ids.index(self.pad_token_id) else: __snake_case : Dict = len(lowerCamelCase_) __snake_case : Union[str, Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowerCamelCase_ , top_spans=lowerCamelCase_ , ) 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=lowerCamelCase_ , start_index=lowerCamelCase_ , end_index=lowerCamelCase_ , text=self.decode(sequence_ids[start_index : end_index + 1]) , )) if len(lowerCamelCase_) >= num_spans: break return nbest_spans_predictions[:num_spans] def _lowercase (self : List[Any] , _A : List[int] , _A : List[int] , _A : int , _A : int , ) -> Tuple: __snake_case : int = [] for start_index, start_score in enumerate(lowerCamelCase_): 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)) __snake_case : Dict = sorted(lowerCamelCase_ , key=lambda _A: x[1] , reverse=lowerCamelCase_) __snake_case : Dict = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(f"Wrong span indices: [{start_index}:{end_index}]") __snake_case : str = end_index - start_index + 1 if length > max_answer_length: raise ValueError(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(lowerCamelCase_) == top_spans: break return chosen_span_intervals @add_end_docstrings(__lowerCAmelCase ) class UpperCamelCase ( __lowerCAmelCase , __lowerCAmelCase ): UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES UpperCAmelCase : List[Any] = READER_PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : str = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : Dict = READER_PRETRAINED_INIT_CONFIGURATION UpperCAmelCase : int = ["""input_ids""", """attention_mask"""]
172
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { """microsoft/trocr-base-handwritten""": ( """https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json""" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = """trocr""" __lowerCAmelCase = ["""past_key_values"""] __lowerCAmelCase = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self : Optional[Any] , lowerCamelCase_ : Optional[int]=5_0265 , lowerCamelCase_ : Optional[int]=1024 , lowerCamelCase_ : List[Any]=12 , lowerCamelCase_ : Any=16 , lowerCamelCase_ : Tuple=4096 , lowerCamelCase_ : Tuple="gelu" , lowerCamelCase_ : List[str]=512 , lowerCamelCase_ : Union[str, Any]=0.1 , lowerCamelCase_ : List[str]=0.0 , lowerCamelCase_ : Optional[int]=0.0 , lowerCamelCase_ : Union[str, Any]=2 , lowerCamelCase_ : Tuple=0.0_2 , lowerCamelCase_ : Union[str, Any]=0.0 , lowerCamelCase_ : str=True , lowerCamelCase_ : List[Any]=False , lowerCamelCase_ : List[str]=True , lowerCamelCase_ : List[Any]=True , lowerCamelCase_ : List[str]=1 , lowerCamelCase_ : Optional[Any]=0 , lowerCamelCase_ : List[Any]=2 , **lowerCamelCase_ : Union[str, Any] , ): """simple docstring""" UpperCamelCase = vocab_size UpperCamelCase = d_model UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = activation_function UpperCamelCase = max_position_embeddings UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = init_std UpperCamelCase = decoder_layerdrop UpperCamelCase = use_cache UpperCamelCase = scale_embedding UpperCamelCase = use_learned_position_embeddings UpperCamelCase = layernorm_embedding super().__init__( pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , decoder_start_token_id=lowerCamelCase_ , **lowerCamelCase_ , )
343
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = ShapEImgaImgPipeline SCREAMING_SNAKE_CASE = ['image'] SCREAMING_SNAKE_CASE = ['image'] SCREAMING_SNAKE_CASE = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] SCREAMING_SNAKE_CASE = False @property def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Any: """simple docstring""" return 32 @property def _SCREAMING_SNAKE_CASE ( self: Tuple) -> str: """simple docstring""" return 32 @property def _SCREAMING_SNAKE_CASE ( self: List[str]) -> List[str]: """simple docstring""" return self.time_input_dim * 4 @property def _SCREAMING_SNAKE_CASE ( self: Dict) -> str: """simple docstring""" return 8 @property def _SCREAMING_SNAKE_CASE ( self: Dict) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) __lowerCAmelCase : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __lowerCAmelCase : List[Any] = CLIPVisionModel(_SCREAMING_SNAKE_CASE) return model @property def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> int: """simple docstring""" __lowerCAmelCase : Union[str, Any] = CLIPImageProcessor( crop_size=224 , do_center_crop=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE , do_resize=_SCREAMING_SNAKE_CASE , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor @property def _SCREAMING_SNAKE_CASE ( self: str) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0) __lowerCAmelCase : Any = { "num_attention_heads": 2, "attention_head_dim": 16, "embedding_dim": self.time_input_dim, "num_embeddings": 32, "embedding_proj_dim": self.text_embedder_hidden_size, "time_embed_dim": self.time_embed_dim, "num_layers": 1, "clip_embed_dim": self.time_input_dim * 2, "additional_embeddings": 0, "time_embed_act_fn": "gelu", "norm_in_type": "layer", "embedding_proj_norm_type": "layer", "encoder_hid_proj_type": None, "added_emb_type": None, } __lowerCAmelCase : int = PriorTransformer(**_SCREAMING_SNAKE_CASE) return model @property def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) __lowerCAmelCase : Optional[int] = { "param_shapes": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), "d_latent": self.time_input_dim, "d_hidden": self.renderer_dim, "n_output": 12, "background": ( 0.1, 0.1, 0.1, ), } __lowerCAmelCase : Any = ShapERenderer(**_SCREAMING_SNAKE_CASE) return model def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Any: """simple docstring""" __lowerCAmelCase : Dict = self.dummy_prior __lowerCAmelCase : Dict = self.dummy_image_encoder __lowerCAmelCase : Tuple = self.dummy_image_processor __lowerCAmelCase : Any = self.dummy_renderer __lowerCAmelCase : Tuple = HeunDiscreteScheduler( beta_schedule="exp" , num_train_timesteps=1024 , prediction_type="sample" , use_karras_sigmas=_SCREAMING_SNAKE_CASE , clip_sample=_SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) __lowerCAmelCase : Tuple = { "prior": prior, "image_encoder": image_encoder, "image_processor": image_processor, "renderer": renderer, "scheduler": scheduler, } return components def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict=0) -> Dict: """simple docstring""" __lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE)).to(_SCREAMING_SNAKE_CASE) if str(_SCREAMING_SNAKE_CASE).startswith("mps"): __lowerCAmelCase : Tuple = torch.manual_seed(_SCREAMING_SNAKE_CASE) else: __lowerCAmelCase : str = torch.Generator(device=_SCREAMING_SNAKE_CASE).manual_seed(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = { "image": input_image, "generator": generator, "num_inference_steps": 1, "frame_size": 32, "output_type": "np", } return inputs def _SCREAMING_SNAKE_CASE ( self: str) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : int = "cpu" __lowerCAmelCase : Tuple = self.get_dummy_components() __lowerCAmelCase : int = self.pipeline_class(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = pipe.to(_SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)) __lowerCAmelCase : List[str] = output.images[0] __lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __lowerCAmelCase : int = np.array( [ 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def _SCREAMING_SNAKE_CASE ( self: Dict) -> Any: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2]) def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> int: """simple docstring""" __lowerCAmelCase : int = torch_device == "cpu" __lowerCAmelCase : List[Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_SCREAMING_SNAKE_CASE , relax_max_difference=_SCREAMING_SNAKE_CASE , ) def _SCREAMING_SNAKE_CASE ( self: Tuple) -> List[Any]: """simple docstring""" __lowerCAmelCase : List[Any] = self.get_dummy_components() __lowerCAmelCase : Optional[int] = self.pipeline_class(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = pipe.to(_SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = 1 __lowerCAmelCase : Optional[int] = 2 __lowerCAmelCase : str = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE) for key in inputs.keys(): if key in self.batch_params: __lowerCAmelCase : Dict = batch_size * [inputs[key]] __lowerCAmelCase : Optional[Any] = pipe(**_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE)[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: Any) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> List[str]: """simple docstring""" __lowerCAmelCase : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png") __lowerCAmelCase : Optional[int] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/test_shap_e_img2img_out.npy") __lowerCAmelCase : List[str] = ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img") __lowerCAmelCase : Dict = pipe.to(_SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : int = torch.Generator(device=_SCREAMING_SNAKE_CASE).manual_seed(0) __lowerCAmelCase : Any = pipe( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="np" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
58
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case : List[str] = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Optional[Any] = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys __snake_case : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
58
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase ( unittest.TestCase ): @slow def A_ ( self : int ) -> Any: lowerCamelCase__ : Optional[Any] = AutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' , return_dict=UpperCAmelCase ).to(UpperCAmelCase ) lowerCamelCase__ : str = AutoTokenizer.from_pretrained('google/mt5-small' ) lowerCamelCase__ : Any = tokenizer('Hello there' , return_tensors='pt' ).input_ids lowerCamelCase__ : Tuple = tokenizer('Hi I am' , return_tensors='pt' ).input_ids lowerCamelCase__ : Optional[int] = model(input_ids.to(UpperCAmelCase ) , labels=labels.to(UpperCAmelCase ) ).loss lowerCamelCase__ : Dict = -(labels.shape[-1] * loss.item()) lowerCamelCase__ : Optional[int] = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
50
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: _UpperCamelCase = None _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} _UpperCamelCase = { 'vocab_file': { 'facebook/mbart-large-en-ro': ( 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model' ), 'facebook/mbart-large-cc25': ( 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model' ), }, 'tokenizer_file': { 'facebook/mbart-large-en-ro': 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json', 'facebook/mbart-large-cc25': 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json', }, } _UpperCamelCase = { 'facebook/mbart-large-en-ro': 1024, 'facebook/mbart-large-cc25': 1024, } # fmt: off _UpperCamelCase = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN'] class lowerCamelCase_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ =VOCAB_FILES_NAMES a_ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ =PRETRAINED_VOCAB_FILES_MAP a_ =["""input_ids""", """attention_mask"""] a_ =MBartTokenizer a_ =[] a_ =[] def __init__( self : Optional[Any] , _a : Optional[int]=None , _a : Any=None , _a : Any="<s>" , _a : Optional[Any]="</s>" , _a : List[str]="</s>" , _a : List[Any]="<s>" , _a : Union[str, Any]="<unk>" , _a : str="<pad>" , _a : Any="<mask>" , _a : Optional[Any]=None , _a : str=None , _a : Tuple=None , **_a : Dict , ) -> List[str]: # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase : List[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( vocab_file=_a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , src_lang=_a , tgt_lang=_a , additional_special_tokens=_a , **_a , ) __lowerCamelCase : Optional[Any] = vocab_file __lowerCamelCase : List[str] = False if not self.vocab_file else True __lowerCamelCase : str = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} ) __lowerCamelCase : Optional[Any] = { lang_code: self.convert_tokens_to_ids(_a ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __lowerCamelCase : Optional[Any] = src_lang if src_lang is not None else 'en_XX' __lowerCamelCase : int = self.convert_tokens_to_ids(self._src_lang ) __lowerCamelCase : List[str] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _lowercase ( self : List[Any] ) -> str: return self._src_lang @src_lang.setter def _lowercase ( self : Union[str, Any] , _a : str ) -> None: __lowerCamelCase : Union[str, Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowercase ( self : List[Any] , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _lowercase ( self : int , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: __lowerCamelCase : Optional[int] = [self.sep_token_id] __lowerCamelCase : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _lowercase ( self : Optional[Any] , _a : Optional[Any] , _a : str , _a : Optional[str] , _a : Optional[str] , **_a : Optional[int] ) -> Any: if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) __lowerCamelCase : Optional[Any] = src_lang __lowerCamelCase : Dict = self(_a , add_special_tokens=_a , return_tensors=_a , **_a ) __lowerCamelCase : Tuple = self.convert_tokens_to_ids(_a ) __lowerCamelCase : Optional[Any] = tgt_lang_id return inputs def _lowercase ( self : Any , _a : List[str] , _a : str = "en_XX" , _a : Optional[List[str]] = None , _a : str = "ro_RO" , **_a : Tuple , ) -> BatchEncoding: __lowerCamelCase : List[Any] = src_lang __lowerCamelCase : str = tgt_lang return super().prepare_seqaseq_batch(_a , _a , **_a ) def _lowercase ( self : List[Any] ) -> Any: return self.set_src_lang_special_tokens(self.src_lang ) def _lowercase ( self : Dict ) -> Optional[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase ( self : Tuple , _a : List[str] ) -> None: __lowerCamelCase : Tuple = self.convert_tokens_to_ids(_a ) __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : List[str] = [self.eos_token_id, self.cur_lang_code] __lowerCamelCase : Dict = self.convert_ids_to_tokens(self.prefix_tokens ) __lowerCamelCase : Optional[Any] = self.convert_ids_to_tokens(self.suffix_tokens ) __lowerCamelCase : Union[str, Any] = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _lowercase ( self : Optional[Any] , _a : str ) -> None: __lowerCamelCase : Union[str, Any] = self.convert_tokens_to_ids(_a ) __lowerCamelCase : int = [] __lowerCamelCase : List[str] = [self.eos_token_id, self.cur_lang_code] __lowerCamelCase : int = self.convert_ids_to_tokens(self.prefix_tokens ) __lowerCamelCase : Any = self.convert_ids_to_tokens(self.suffix_tokens ) __lowerCamelCase : Optional[int] = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _lowercase ( self : Any , _a : str , _a : Optional[str] = None ) -> Tuple[str]: 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(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory.' ) return __lowerCamelCase : List[str] = os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
208
0
def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : Union[str, Any] ): '''simple docstring''' lowerCamelCase = len(lowerCamelCase__ ) + 1 lowerCamelCase = len(lowerCamelCase__ ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowerCamelCase = [[0 for i in range(lowerCamelCase__ )] for j in range(lowerCamelCase__ )] # since string of zero length match pattern of zero length lowerCamelCase = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , lowerCamelCase__ ): lowerCamelCase = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , lowerCamelCase__ ): lowerCamelCase = dp[0][j - 2] if pattern[j - 1] == """*""" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , lowerCamelCase__ ): for j in range(1 , lowerCamelCase__ ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowerCamelCase = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowerCamelCase = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowerCamelCase = dp[i - 1][j] else: lowerCamelCase = 0 else: lowerCamelCase = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") UpperCAmelCase : int = "aab" UpperCAmelCase : List[str] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"""{input_string} matches the given pattern {pattern}""") else: print(f"""{input_string} does not match with the given pattern {pattern}""")
354
def __lowerCamelCase ( ): '''simple docstring''' lowerCamelCase = [] lowerCamelCase = 1 while len(lowerCamelCase__ ) < 1E6: constant.append(str(lowerCamelCase__ ) ) i += 1 lowerCamelCase = """""".join(lowerCamelCase__ ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[99999] ) * int(constant[999999] ) ) if __name__ == "__main__": print(solution())
66
0
"""simple docstring""" import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__:int = 'Hello world! cécé herlolip' SCREAMING_SNAKE_CASE__:List[Any] = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def _lowerCamelCase( a , a ): __a = BertAbsConfig( temp_dir="." , finetune_bert=a , large=a , share_emb=a , use_bert_emb=a , encoder="bert" , max_pos=5_1_2 , enc_layers=6 , enc_hidden_size=5_1_2 , enc_heads=8 , enc_ff_size=5_1_2 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_6_8 , dec_heads=8 , dec_ff_size=2_0_4_8 , dec_dropout=0.2 , ) __a = torch.load(a , lambda a , a : storage ) __a = AbsSummarizer(a , torch.device("cpu" ) , a ) original.eval() __a = BertAbsSummarizer(a , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models\' outputs are identical" ) __a = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs __a = tokenizer.encode("This is sample éàalj\'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(a )) ) __a = torch.tensor(a ).unsqueeze(0 ) __a = tokenizer.encode("This is sample 3 éàalj\'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(a )) ) __a = torch.tensor(a ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass __a = encoder_input_ids __a = decoder_input_ids __a = __a = None __a = None __a = __a = None __a = __a = None __a = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical __a = original(a , a , a , a , a , a , a )[0] __a = original.generator(a ) __a = new_model( a , a , a , a , a )[0] __a = new_model.generator(a ) __a = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(a ) ) __a = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(a ) ) __a = torch.allclose(a , a , atol=1E-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model\'s state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Any = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) SCREAMING_SNAKE_CASE__:Dict = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
261
import requests snake_case__ : int = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=' def _a ( lowerCamelCase: str ) -> None: '''simple docstring''' __A = 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>')
117
0
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE (a__ , a__ , unittest.TestCase ): lowerCAmelCase = AutoencoderKL lowerCAmelCase = '''sample''' lowerCAmelCase = 1E-2 @property def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = 4 __A : Any = 3 __A : Tuple = (32, 32) __A : Optional[Any] = floats_tensor((batch_size, num_channels) + sizes).to(_UpperCAmelCase) return {"sample": image} @property def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' return (3, 32, 32) @property def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' return (3, 32, 32) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } __A : Any = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' pass @unittest.skipIf(torch_device == 'mps' , 'Gradient checkpointing skipped on MPS') def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A ,__A : List[Any] = self.prepare_init_args_and_inputs_for_common() __A : Any = self.model_class(**_UpperCAmelCase) model.to(_UpperCAmelCase) assert not model.is_gradient_checkpointing and model.training __A : List[str] = model(**_UpperCAmelCase).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __A : Dict = torch.randn_like(_UpperCAmelCase) __A : List[Any] = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __A : Optional[int] = self.model_class(**_UpperCAmelCase) # clone model model_a.load_state_dict(model.state_dict()) model_a.to(_UpperCAmelCase) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __A : Dict = model_a(**_UpperCAmelCase).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __A : Any = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5) __A : Any = dict(model.named_parameters()) __A : Union[str, Any] = dict(model_a.named_parameters()) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5)) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A ,__A : Optional[int] = AutoencoderKL.from_pretrained('fusing/autoencoder-kl-dummy' , output_loading_info=_UpperCAmelCase) self.assertIsNotNone(_UpperCAmelCase) self.assertEqual(len(loading_info['missing_keys']) , 0) model.to(_UpperCAmelCase) __A : int = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[Any] = AutoencoderKL.from_pretrained('fusing/autoencoder-kl-dummy') __A : Any = model.to(_UpperCAmelCase) model.eval() if torch_device == "mps": __A : Dict = torch.manual_seed(0) else: __A : List[str] = torch.Generator(device=_UpperCAmelCase).manual_seed(0) __A : Any = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0) , ) __A : Union[str, Any] = image.to(_UpperCAmelCase) with torch.no_grad(): __A : Any = model(_UpperCAmelCase , sample_posterior=_UpperCAmelCase , generator=_UpperCAmelCase).sample __A : List[Any] = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __A : Optional[int] = torch.tensor( [ -4.0_0_7_8e-0_1, -3.8_3_2_3e-0_4, -1.2_6_8_1e-0_1, -1.1_4_6_2e-0_1, 2.0_0_9_5e-0_1, 1.0_8_9_3e-0_1, -8.8_2_4_7e-0_2, -3.0_3_6_1e-0_1, -9.8_6_4_4e-0_3, ]) elif torch_device == "cpu": __A : str = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026]) else: __A : str = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485]) self.assertTrue(torch_all_close(_UpperCAmelCase , _UpperCAmelCase , rtol=1e-2)) @slow class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' return F'gaussian_noise_s={seed}_shape={"_".join([str(_UpperCAmelCase) for s in shape])}.npy' def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase=0 , _UpperCAmelCase=(4, 3, 512, 512) , _UpperCAmelCase=False): '''simple docstring''' __A : List[Any] = torch.floataa if fpaa else torch.floataa __A : str = torch.from_numpy(load_hf_numpy(self.get_file_format(_UpperCAmelCase , _UpperCAmelCase))).to(_UpperCAmelCase).to(_UpperCAmelCase) return image def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase="CompVis/stable-diffusion-v1-4" , _UpperCAmelCase=False): '''simple docstring''' __A : Tuple = 'fp16' if fpaa else None __A : int = torch.floataa if fpaa else torch.floataa __A : int = AutoencoderKL.from_pretrained( _UpperCAmelCase , subfolder='vae' , torch_dtype=_UpperCAmelCase , revision=_UpperCAmelCase , ) model.to(_UpperCAmelCase).eval() return model def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase=0): '''simple docstring''' if torch_device == "mps": return torch.manual_seed(_UpperCAmelCase) return torch.Generator(device=_UpperCAmelCase).manual_seed(_UpperCAmelCase) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ]) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Dict = self.get_sd_vae_model() __A : Tuple = self.get_sd_image(_UpperCAmelCase) __A : Optional[Any] = self.get_generator(_UpperCAmelCase) with torch.no_grad(): __A : List[str] = model(_UpperCAmelCase , generator=_UpperCAmelCase , sample_posterior=_UpperCAmelCase).sample assert sample.shape == image.shape __A : List[str] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __A : Optional[int] = torch.tensor(expected_slice_mps if torch_device == 'mps' else expected_slice) assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=3e-3) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ]) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Any = self.get_sd_vae_model(fpaa=_UpperCAmelCase) __A : int = self.get_sd_image(_UpperCAmelCase , fpaa=_UpperCAmelCase) __A : List[Any] = self.get_generator(_UpperCAmelCase) with torch.no_grad(): __A : Union[str, Any] = model(_UpperCAmelCase , generator=_UpperCAmelCase , sample_posterior=_UpperCAmelCase).sample assert sample.shape == image.shape __A : int = sample[-1, -2:, :2, -2:].flatten().float().cpu() __A : List[str] = torch.tensor(_UpperCAmelCase) assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=1e-2) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ]) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Optional[Any] = self.get_sd_vae_model() __A : Tuple = self.get_sd_image(_UpperCAmelCase) with torch.no_grad(): __A : Union[str, Any] = model(_UpperCAmelCase).sample assert sample.shape == image.shape __A : List[str] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __A : Dict = torch.tensor(expected_slice_mps if torch_device == 'mps' else expected_slice) assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=3e-3) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ]) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : List[str] = self.get_sd_vae_model() __A : Dict = self.get_sd_image(_UpperCAmelCase , shape=(3, 4, 64, 64)) with torch.no_grad(): __A : Optional[Any] = model.decode(_UpperCAmelCase).sample assert list(sample.shape) == [3, 3, 512, 512] __A : Union[str, Any] = sample[-1, -2:, :2, -2:].flatten().cpu() __A : Optional[int] = torch.tensor(_UpperCAmelCase) assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=1e-3) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ]) @require_torch_gpu def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Optional[int] = self.get_sd_vae_model(fpaa=_UpperCAmelCase) __A : List[str] = self.get_sd_image(_UpperCAmelCase , shape=(3, 4, 64, 64) , fpaa=_UpperCAmelCase) with torch.no_grad(): __A : Any = model.decode(_UpperCAmelCase).sample assert list(sample.shape) == [3, 3, 512, 512] __A : Dict = sample[-1, -2:, :2, -2:].flatten().float().cpu() __A : Optional[int] = torch.tensor(_UpperCAmelCase) assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=5e-3) @parameterized.expand([(13,), (16,), (27,)]) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='xformers is not required when using PyTorch 2.0.') def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' __A : Tuple = self.get_sd_vae_model(fpaa=_UpperCAmelCase) __A : Optional[Any] = self.get_sd_image(_UpperCAmelCase , shape=(3, 4, 64, 64) , fpaa=_UpperCAmelCase) with torch.no_grad(): __A : List[Any] = model.decode(_UpperCAmelCase).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __A : Tuple = model.decode(_UpperCAmelCase).sample assert list(sample.shape) == [3, 3, 512, 512] assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=1e-1) @parameterized.expand([(13,), (16,), (37,)]) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='xformers is not required when using PyTorch 2.0.') def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' __A : Any = self.get_sd_vae_model() __A : Tuple = self.get_sd_image(_UpperCAmelCase , shape=(3, 4, 64, 64)) with torch.no_grad(): __A : Union[str, Any] = model.decode(_UpperCAmelCase).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __A : List[str] = model.decode(_UpperCAmelCase).sample assert list(sample.shape) == [3, 3, 512, 512] assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=1e-2) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ]) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Dict = self.get_sd_vae_model() __A : Dict = self.get_sd_image(_UpperCAmelCase) __A : Tuple = self.get_generator(_UpperCAmelCase) with torch.no_grad(): __A : str = model.encode(_UpperCAmelCase).latent_dist __A : Optional[int] = dist.sample(generator=_UpperCAmelCase) assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __A : List[Any] = sample[0, -1, -3:, -3:].flatten().cpu() __A : List[Any] = torch.tensor(_UpperCAmelCase) __A : Union[str, Any] = 3e-3 if torch_device != 'mps' else 1e-2 assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , atol=_UpperCAmelCase)
190
'''simple docstring''' import argparse lowercase__ : Any = '''docs/source/_static/js/custom.js''' def _lowerCAmelCase ( __snake_case : Union[str, Any] ) -> str: with open(__snake_case , encoding='utf-8' , newline='\n' ) as f: __A : Optional[Any] = f.readlines() __A : List[str] = 0 # First let's put the right version while not lines[index].startswith('const stableVersion =' ): index += 1 __A : Tuple = f'const stableVersion = "v{version}"\n' # Then update the dictionary while not lines[index].startswith('const versionMapping = {' ): index += 1 # We go until the end while not lines[index].startswith('}' ): index += 1 # We add the new version at the end lines[index - 1] += f' "v{version}": "v{version}",\n' with open(__snake_case , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(__snake_case ) if __name__ == "__main__": lowercase__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--version''', help='''Release version.''') lowercase__ : List[str] = parser.parse_args() update_custom_js(args.version)
190
1
"""simple docstring""" import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def _snake_case ( UpperCAmelCase_ : int ): if hor == 128: A__ = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") A__ = (32, 128, 256) A__ = ("""UpResnetBlock1D""", """UpResnetBlock1D""") elif hor == 32: A__ = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") A__ = (32, 64, 128, 256) A__ = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""") A__ = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) A__ = model.state_dict() A__ = { """down_block_types""": down_block_types, """block_out_channels""": block_out_channels, """up_block_types""": up_block_types, """layers_per_block""": 1, """use_timestep_embedding""": True, """out_block_type""": """OutConv1DBlock""", """norm_num_groups""": 8, """downsample_each_block""": False, """in_channels""": 14, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """flip_sin_to_cos""": False, """freq_shift""": 1, """sample_size""": 6_5536, """mid_block_type""": """MidResTemporalBlock1D""", """act_fn""": """mish""", } A__ = UNetaDModel(**UpperCAmelCase_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) A__ = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): A__ = state_dict.pop(UpperCAmelCase_ ) hf_value_function.load_state_dict(UpperCAmelCase_ ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , """w""" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) def _snake_case ( ): A__ = { """in_channels""": 14, """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""), """up_block_types""": (), """out_block_type""": """ValueFunction""", """mid_block_type""": """ValueFunctionMidBlock1D""", """block_out_channels""": (32, 64, 128, 256), """layers_per_block""": 1, """downsample_each_block""": True, """sample_size""": 6_5536, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """use_timestep_embedding""": True, """flip_sin_to_cos""": False, """freq_shift""": 1, """norm_num_groups""": 8, """act_fn""": """mish""", } A__ = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" ) A__ = model A__ = UNetaDModel(**UpperCAmelCase_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) A__ = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): A__ = state_dict.pop(UpperCAmelCase_ ) hf_value_function.load_state_dict(UpperCAmelCase_ ) torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""" ) with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""" ) as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) if __name__ == "__main__": unet(3_2) # unet(128) value_function()
335
"""simple docstring""" import math class a : """simple docstring""" def __init__( self: List[Any] , UpperCamelCase: List[str]=0 ): # a graph with Node 0,1,...,N-1 """simple docstring""" A__ = n A__ = [ [math.inf for j in range(0 , UpperCamelCase )] for i in range(0 , UpperCamelCase ) ] # adjacency matrix for weight A__ = [ [math.inf for j in range(0 , UpperCamelCase )] for i in range(0 , UpperCamelCase ) ] # dp[i][j] stores minimum distance from i to j def UpperCamelCase ( self: Union[str, Any] , UpperCamelCase: Optional[int] , UpperCamelCase: Union[str, Any] , UpperCamelCase: Tuple ): """simple docstring""" A__ = w def UpperCamelCase ( self: int ): """simple docstring""" for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): A__ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def UpperCamelCase ( self: int , UpperCamelCase: List[str] , UpperCamelCase: Dict ): """simple docstring""" return self.dp[u][v] if __name__ == "__main__": SCREAMING_SNAKE_CASE_ : List[Any] = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
335
1
'''simple docstring''' import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging _SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = r"\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n" class _snake_case ( lowercase_ ): @add_start_docstrings(a__ ) def __call__( self , a__ , a__ , **a__ ) -> bool: '''simple docstring''' raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class _snake_case ( lowercase_ ): def __init__( self , a__ , a__ = None ) -> int: '''simple docstring''' snake_case_ = max_length snake_case_ = max_position_embeddings @add_start_docstrings(a__ ) def __call__( self , a__ , a__ , **a__ ) -> bool: '''simple docstring''' snake_case_ = input_ids.shape[-1] snake_case_ = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F'maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ' "exceptions, performance degradation, or nothing at all." ) return is_done class _snake_case ( lowercase_ ): def __init__( self , a__ , a__ ) -> List[str]: '''simple docstring''' warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F'Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ' "with `max_length = start_length + max_new_tokens` instead." , a__ , ) snake_case_ = start_length snake_case_ = max_new_tokens snake_case_ = start_length + max_new_tokens @add_start_docstrings(a__ ) def __call__( self , a__ , a__ , **a__ ) -> bool: '''simple docstring''' return input_ids.shape[-1] >= self.max_length class _snake_case ( lowercase_ ): def __init__( self , a__ , a__ = None ) -> int: '''simple docstring''' snake_case_ = max_time snake_case_ = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(a__ ) def __call__( self , a__ , a__ , **a__ ) -> bool: '''simple docstring''' return time.time() - self.initial_timestamp > self.max_time class _snake_case ( lowercase_ ): @add_start_docstrings(a__ ) def __call__( self , a__ , a__ , **a__ ) -> bool: '''simple docstring''' return any(criteria(a__ , a__ ) for criteria in self ) @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' for stopping_criterium in self: if isinstance(a__ , a__ ): return stopping_criterium.max_length elif isinstance(a__ , a__ ): return stopping_criterium.max_length return None def UpperCamelCase_( snake_case : StoppingCriteriaList , snake_case : int ): '''simple docstring''' snake_case_ = stopping_criteria.max_length snake_case_ = deepcopy(snake_case ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , snake_case ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=snake_case ) ) return new_stopping_criteria
92
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = int(snake_case ) assert noofclusters < len(snake_case ) # Find out the dimensionality snake_case_ = len(vectors[0] ) # Will help select random centroids from among the available vectors snake_case_ = list(range(len(snake_case ) ) ) shuffle(snake_case ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. snake_case_ = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION snake_case_ = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points snake_case_ = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(snake_case ) ] ##These nodes will assign the centroid Variables the appropriate ##values snake_case_ = tf.placeholder("float64" , [dim] ) snake_case_ = [] for centroid in centroids: cent_assigns.append(tf.assign(snake_case , snake_case ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) snake_case_ = [tf.Variable(0 ) for i in range(len(snake_case ) )] ##These nodes will assign an assignment Variable the appropriate ##value snake_case_ = tf.placeholder("int32" ) snake_case_ = [] for assignment in assignments: cluster_assigns.append(tf.assign(snake_case , snake_case ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input snake_case_ = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors snake_case_ = tf.reduce_mean(snake_case , 0 ) ##Node for computing Euclidean distances # Placeholders for input snake_case_ = tf.placeholder("float" , [dim] ) snake_case_ = tf.placeholder("float" , [dim] ) snake_case_ = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(snake_case , snake_case ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input snake_case_ = tf.placeholder("float" , [noofclusters] ) snake_case_ = tf.argmin(snake_case , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. snake_case_ = tf.initialize_all_variables() # Initialize all variables sess.run(snake_case ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. snake_case_ = 1_0_0 for _ in range(snake_case ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(snake_case ) ): snake_case_ = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. snake_case_ = [ sess.run(snake_case , feed_dict={va: vect, va: sess.run(snake_case )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input snake_case_ = sess.run( snake_case , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(snake_case ): # Collect all the vectors assigned to this cluster snake_case_ = [ vectors[i] for i in range(len(snake_case ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location snake_case_ = sess.run( snake_case , feed_dict={mean_input: array(snake_case )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments snake_case_ = sess.run(snake_case ) snake_case_ = sess.run(snake_case ) return centroids, assignments
92
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 a_ ( a__ , a__ , a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = StableUnCLIPImgaImgPipeline __SCREAMING_SNAKE_CASE : List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : Any = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __SCREAMING_SNAKE_CASE : Tuple = frozenset([] ) def __lowerCAmelCase ( self ) ->Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[Any] = 32 SCREAMING_SNAKE_CASE : Tuple = embedder_hidden_size # image encoding components SCREAMING_SNAKE_CASE : int = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=_lowerCamelCase , projection_dim=_lowerCamelCase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = StableUnCLIPImageNormalizer(embedding_dim=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_lowerCamelCase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = 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=_lowerCamelCase , layers_per_block=1 , upcast_attention=_lowerCamelCase , use_linear_projection=_lowerCamelCase , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type='''v_prediction''' , set_alpha_to_one=_lowerCamelCase , steps_offset=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL() SCREAMING_SNAKE_CASE : Optional[Any] = { # 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 __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 , _lowerCamelCase=True ) ->Optional[int]: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : Optional[int] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) if pil_image: SCREAMING_SNAKE_CASE : Any = input_image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : int = input_image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE : List[str] = DiffusionPipeline.numpy_to_pil(_lowerCamelCase )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Tuple = StableUnCLIPImgaImgPipeline(**_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_inputs(_lowerCamelCase ) inputs.update({'''image_embeds''': None} ) SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Tuple = np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : str = torch_device in ['''cpu''', '''mps'''] self._test_attention_slicing_forward_pass(test_max_difference=_lowerCamelCase ) def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Tuple = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=_lowerCamelCase ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __lowerCAmelCase ( self ) ->Optional[int]: self._test_xformers_attention_forwardGenerator_pass(test_max_difference=_lowerCamelCase ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) ->Tuple: SCREAMING_SNAKE_CASE : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) SCREAMING_SNAKE_CASE : Optional[Any] = 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''' ) SCREAMING_SNAKE_CASE : List[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-l-img2img''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe(_lowerCamelCase , '''anime turle''' , generator=_lowerCamelCase , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Optional[Any]: SCREAMING_SNAKE_CASE : List[str] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''' ) SCREAMING_SNAKE_CASE : Optional[int] = 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''' ) SCREAMING_SNAKE_CASE : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipe(_lowerCamelCase , '''anime turle''' , generator=_lowerCamelCase , output_type='''np''' ) SCREAMING_SNAKE_CASE : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : Union[str, Any] = 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() SCREAMING_SNAKE_CASE : str = StableUnCLIPImgaImgPipeline.from_pretrained( '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Dict = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE : Dict = pipe( _lowerCamelCase , '''anime turtle''' , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE : Any = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
313
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class a_ : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = True , _lowerCamelCase = False ) ->Any: SCREAMING_SNAKE_CASE : str = scheduler SCREAMING_SNAKE_CASE : List[str] = optimizers if isinstance(_lowerCamelCase , (list, tuple) ) else [optimizers] SCREAMING_SNAKE_CASE : Union[str, Any] = split_batches SCREAMING_SNAKE_CASE : List[Any] = step_with_optimizer SCREAMING_SNAKE_CASE : List[str] = GradientState() def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->Optional[Any]: if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*_lowerCamelCase , **_lowerCamelCase ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*_lowerCamelCase , **_lowerCamelCase ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step SCREAMING_SNAKE_CASE : List[str] = AcceleratorState().num_processes for _ in range(_lowerCamelCase ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*_lowerCamelCase , **_lowerCamelCase ) else: self.scheduler.step(*_lowerCamelCase , **_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Union[str, Any]: return self.scheduler.get_last_lr() def __lowerCAmelCase ( self ) ->List[str]: return self.scheduler.state_dict() def __lowerCAmelCase ( self , _lowerCamelCase ) ->Optional[Any]: self.scheduler.load_state_dict(_lowerCamelCase ) def __lowerCAmelCase ( self ) ->Any: return self.scheduler.get_lr() def __lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ) ->List[str]: return self.scheduler.print_lr(*_lowerCamelCase , **_lowerCamelCase )
313
1
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __SCREAMING_SNAKE_CASE : @staticmethod def _lowerCamelCase ( *__lowerCAmelCase , **__lowerCAmelCase ): pass @is_pipeline_test @require_vision @require_timm @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case : Any = MODEL_FOR_OBJECT_DETECTION_MAPPING def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = ObjectDetectionPipeline(model=__lowerCAmelCase , image_processor=__lowerCAmelCase ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__lowerCAmelCase ) , 0 ) for detected_object in outputs: self.assertEqual( __lowerCAmelCase , { """score""": ANY(__lowerCAmelCase ), """label""": ANY(__lowerCAmelCase ), """box""": {"""xmin""": ANY(__lowerCAmelCase ), """ymin""": ANY(__lowerCAmelCase ), """xmax""": ANY(__lowerCAmelCase ), """ymax""": ANY(__lowerCAmelCase )}, } , ) import datasets UpperCamelCase__ = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) UpperCamelCase__ = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] UpperCamelCase__ = object_detector(__lowerCAmelCase , threshold=0.0 ) self.assertEqual(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) for outputs in batch_outputs: self.assertGreater(len(__lowerCAmelCase ) , 0 ) for detected_object in outputs: self.assertEqual( __lowerCAmelCase , { """score""": ANY(__lowerCAmelCase ), """label""": ANY(__lowerCAmelCase ), """box""": {"""xmin""": ANY(__lowerCAmelCase ), """ymin""": ANY(__lowerCAmelCase ), """xmax""": ANY(__lowerCAmelCase ), """ymax""": ANY(__lowerCAmelCase )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def _lowerCamelCase ( self ): pass @require_torch def _lowerCamelCase ( self ): UpperCamelCase__ = """hf-internal-testing/tiny-detr-mobilenetsv3""" UpperCamelCase__ = AutoModelForObjectDetection.from_pretrained(__lowerCAmelCase ) UpperCamelCase__ = AutoFeatureExtractor.from_pretrained(__lowerCAmelCase ) UpperCamelCase__ = ObjectDetectionPipeline(model=__lowerCAmelCase , feature_extractor=__lowerCAmelCase ) UpperCamelCase__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) UpperCamelCase__ = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def _lowerCamelCase ( self ): UpperCamelCase__ = """facebook/detr-resnet-50""" UpperCamelCase__ = AutoModelForObjectDetection.from_pretrained(__lowerCAmelCase ) UpperCamelCase__ = AutoFeatureExtractor.from_pretrained(__lowerCAmelCase ) UpperCamelCase__ = ObjectDetectionPipeline(model=__lowerCAmelCase , feature_extractor=__lowerCAmelCase ) UpperCamelCase__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) UpperCamelCase__ = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def _lowerCamelCase ( self ): UpperCamelCase__ = """facebook/detr-resnet-50""" UpperCamelCase__ = pipeline("""object-detection""" , model=__lowerCAmelCase ) UpperCamelCase__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) UpperCamelCase__ = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def _lowerCamelCase ( self ): UpperCamelCase__ = 0.9985 UpperCamelCase__ = """facebook/detr-resnet-50""" UpperCamelCase__ = pipeline("""object-detection""" , model=__lowerCAmelCase ) UpperCamelCase__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__lowerCAmelCase ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def _lowerCamelCase ( self ): UpperCamelCase__ = """Narsil/layoutlmv3-finetuned-funsd""" UpperCamelCase__ = 0.9993 UpperCamelCase__ = pipeline("""object-detection""" , model=__lowerCAmelCase , threshold=__lowerCAmelCase ) UpperCamelCase__ = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
87
import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def _UpperCamelCase (a__ :int ): """simple docstring""" if hor == 128: UpperCamelCase__ = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") UpperCamelCase__ = (32, 128, 256) UpperCamelCase__ = ("""UpResnetBlock1D""", """UpResnetBlock1D""") elif hor == 32: UpperCamelCase__ = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") UpperCamelCase__ = (32, 64, 128, 256) UpperCamelCase__ = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""") UpperCamelCase__ = torch.load(f"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) UpperCamelCase__ = model.state_dict() UpperCamelCase__ = { """down_block_types""": down_block_types, """block_out_channels""": block_out_channels, """up_block_types""": up_block_types, """layers_per_block""": 1, """use_timestep_embedding""": True, """out_block_type""": """OutConv1DBlock""", """norm_num_groups""": 8, """downsample_each_block""": False, """in_channels""": 14, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """flip_sin_to_cos""": False, """freq_shift""": 1, """sample_size""": 6_5536, """mid_block_type""": """MidResTemporalBlock1D""", """act_fn""": """mish""", } UpperCamelCase__ = UNetaDModel(**a__ ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) UpperCamelCase__ = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): UpperCamelCase__ = state_dict.pop(a__ ) hf_value_function.load_state_dict(a__ ) torch.save(hf_value_function.state_dict() , f"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(f"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , """w""" ) as f: json.dump(a__ , a__ ) def _UpperCamelCase (): """simple docstring""" UpperCamelCase__ = { """in_channels""": 14, """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""), """up_block_types""": (), """out_block_type""": """ValueFunction""", """mid_block_type""": """ValueFunctionMidBlock1D""", """block_out_channels""": (32, 64, 128, 256), """layers_per_block""": 1, """downsample_each_block""": True, """sample_size""": 6_5536, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """use_timestep_embedding""": True, """flip_sin_to_cos""": False, """freq_shift""": 1, """norm_num_groups""": 8, """act_fn""": """mish""", } UpperCamelCase__ = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" ) UpperCamelCase__ = model UpperCamelCase__ = UNetaDModel(**a__ ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) UpperCamelCase__ = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): UpperCamelCase__ = state_dict.pop(a__ ) hf_value_function.load_state_dict(a__ ) torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""" ) with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""" ) as f: json.dump(a__ , a__ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
87
1
'''simple docstring''' import os from math import logaa def snake_case ( UpperCAmelCase = "base_exp.txt" )-> Optional[Any]: """simple docstring""" __A = 0 __A = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) ): __A , __A = list(map(SCREAMING_SNAKE_CASE_ , line.split(',' ) ) ) if x * logaa(SCREAMING_SNAKE_CASE_ ) > largest: __A = x * logaa(SCREAMING_SNAKE_CASE_ ) __A = i + 1 return result if __name__ == "__main__": print(solution())
161
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a__ : def __init__( self , _A , _A=1_3 , _A=3_0 , _A=2 , _A=3 , _A=True , _A=True , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1_0 , _A=0.02 , _A=3 , _A=None , _A=2 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = scope __lowerCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 2 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTForMaskedImageModeling(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForMaskedImageModeling(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) _a : int = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) _a : Optional[Any] = False _a : Tuple = False _a : Tuple = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=False ): """simple docstring""" __lowerCAmelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.model_tester.is_training: return __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __lowerCAmelCase = False __lowerCAmelCase = True for model_class in self.all_model_classes: if model_class in get_values(_A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __lowerCAmelCase = model_class(_A ) model.gradient_checkpointing_enable() model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_A ), *get_values(_A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type['title']}""" ): __lowerCAmelCase = problem_type["title"] __lowerCAmelCase = problem_type["num_labels"] __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) if problem_type["num_labels"] > 1: __lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) __lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_A ) as warning_list: __lowerCAmelCase = model(**_A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DeiTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _a ( ): __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( _A ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ).to(_A ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**_A ) # verify the logits __lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _A ) __lowerCAmelCase = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ) __lowerCAmelCase = inputs.pixel_values.to(_A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowerCAmelCase = model(_A )
92
0
import math from numpy import inf from scipy.integrate import quad def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> float: """simple docstring""" if num <= 0: raise ValueError("math domain error" ) return quad(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ , args=(SCREAMING_SNAKE_CASE_) )[0] def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> float: """simple docstring""" return math.pow(SCREAMING_SNAKE_CASE_ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
60
import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE :Optional[int] = """\ @inproceedings{snover-etal-2006-study, title = \"A Study of Translation Edit Rate with Targeted Human Annotation\", author = \"Snover, Matthew and Dorr, Bonnie and Schwartz, Rich and Micciulla, Linnea and Makhoul, John\", booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\", month = aug # \" 8-12\", year = \"2006\", address = \"Cambridge, Massachusetts, USA\", publisher = \"Association for Machine Translation in the Americas\", url = \"https://aclanthology.org/2006.amta-papers.25\", pages = \"223--231\", } @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ SCREAMING_SNAKE_CASE :Optional[int] = """\ TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu (https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found here: https://github.com/jhclark/tercom. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information. """ SCREAMING_SNAKE_CASE :Tuple = """ Produces TER scores alongside the number of edits and reference length. Args: predictions (list of str): The system stream (a sequence of segments). references (list of list of str): A list of one or more reference streams (each a sequence of segments). normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`. ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`. support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters, as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana. Only applies if `normalized = True`. Defaults to `False`. case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`. Returns: 'score' (float): TER score (num_edits / sum_ref_lengths * 100) 'num_edits' (int): The cumulative number of edits 'ref_length' (float): The cumulative average reference length Examples: Example 1: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\", ... \"What did the TER metric user say to the developer?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"], ... [\"Your jokes are...\", \"...TERrible\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... case_sensitive=True) >>> print(results) {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0} Example 2: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... case_sensitive=True) >>> print(results) {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0} Example 3: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... normalized=True, ... case_sensitive=True) >>> print(results) {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5} Example 4: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... ignore_punct=True, ... case_sensitive=False) >>> print(results) {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0} Example 5: >>> predictions = [\"does this sentence match??\", ... \"what about this sentence?\", ... \"What did the TER metric user say to the developer?\"] >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"], ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"], ... [\"Your jokes are...\", \"...TERrible\"]] >>> ter = datasets.load_metric(\"ter\") >>> results = ter.compute(predictions=predictions, ... references=references, ... ignore_punct=True, ... case_sensitive=False) >>> print(results) {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): def UpperCAmelCase_ ( self )-> Tuple: if version.parse(scb.__version__ ) < version.parse("1.4.12" ): raise ImportWarning( "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n" "You can install it with `pip install \"sacrebleu>=1.4.12\"`." ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="http://www.cs.umd.edu/~snover/tercom/" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"] , reference_urls=[ "https://github.com/jhclark/tercom", ] , ) def UpperCAmelCase_ ( self , _lowercase , _lowercase , _lowercase = False , _lowercase = False , _lowercase = False , _lowercase = False , )-> int: UpperCamelCase_ = len(references[0] ) if any(len(_lowercase ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCamelCase_ = [[refs[i] for refs in references] for i in range(_lowercase )] UpperCamelCase_ = TER( normalized=_lowercase , no_punct=_lowercase , asian_support=_lowercase , case_sensitive=_lowercase , ) UpperCamelCase_ = sb_ter.corpus_score(_lowercase , _lowercase ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
60
1
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase_ ( a): def snake_case__ ( self, __a): '''simple docstring''' return 0.0 def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) _lowerCAmelCase : Optional[int] = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : int = 512 _lowerCAmelCase : Union[str, Any] = [1] + [0] * (size - 1) _lowerCAmelCase : Optional[Any] = [filter_type.process(_lowerCamelCase ) for item in inputs] _lowerCAmelCase : int = [0] * (samplerate - size) # zero-padding outputs += filler _lowerCAmelCase : str = np.abs(np.fft.fft(_lowerCamelCase ) ) _lowerCAmelCase : Union[str, Any] = 20 * np.logaa(_lowerCamelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds _lowerCAmelCase : List[Any] = get_bounds(_lowerCamelCase , _lowerCamelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(_lowerCamelCase ) plt.show() def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = 512 _lowerCAmelCase : Optional[Any] = [1] + [0] * (size - 1) _lowerCAmelCase : str = [filter_type.process(_lowerCamelCase ) for item in inputs] _lowerCAmelCase : Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler _lowerCAmelCase : Optional[Any] = np.angle(np.fft.fft(_lowerCamelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(_lowerCamelCase , -2 * pi ) ) plt.show()
36
'''simple docstring''' import argparse import copy def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : List[str] = {} with open(__magic_name__ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: UpperCAmelCase : List[Any] = [] _list.append([line.split()[1], line.split()[2]] ) UpperCAmelCase : Tuple = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: UpperCAmelCase : Any = [] _list.append([line.split()[0], line.split()[2]] ) UpperCAmelCase : int = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' with open(__magic_name__ ) as f: UpperCAmelCase : List[str] = f.read(1 ) UpperCAmelCase : List[Any] = start_node UpperCAmelCase : Union[str, Any] = [] UpperCAmelCase : Any = start_node UpperCAmelCase : Optional[Any] = 0 while visiting not in first_solution: UpperCAmelCase : Optional[Any] = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__magic_name__ ) and k[0] not in first_solution: UpperCAmelCase : Tuple = k[1] UpperCAmelCase : Dict = k[0] first_solution.append(__magic_name__ ) UpperCAmelCase : int = distance_of_first_solution + int(__magic_name__ ) UpperCAmelCase : str = best_node first_solution.append(__magic_name__ ) UpperCAmelCase : int = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 UpperCAmelCase : str = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase : Optional[Any] = [] for n in solution[1:-1]: UpperCAmelCase : Any = solution.index(__magic_name__ ) for kn in solution[1:-1]: UpperCAmelCase : Dict = solution.index(__magic_name__ ) if n == kn: continue UpperCAmelCase : Tuple = copy.deepcopy(__magic_name__ ) UpperCAmelCase : Optional[int] = kn UpperCAmelCase : List[str] = n UpperCAmelCase : str = 0 for k in _tmp[:-1]: UpperCAmelCase : List[Any] = _tmp[_tmp.index(__magic_name__ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: UpperCAmelCase : List[Any] = distance + int(i[1] ) _tmp.append(__magic_name__ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) UpperCAmelCase : List[str] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __magic_name__ : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowercase ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase : List[Any] = 1 UpperCAmelCase : List[str] = first_solution UpperCAmelCase : str = [] UpperCAmelCase : Union[str, Any] = distance_of_first_solution UpperCAmelCase : Union[str, Any] = solution while count <= iters: UpperCAmelCase : int = find_neighborhood(__magic_name__ , __magic_name__ ) UpperCAmelCase : Any = 0 UpperCAmelCase : List[str] = neighborhood[index_of_best_solution] UpperCAmelCase : Dict = len(__magic_name__ ) - 1 UpperCAmelCase : Dict = False while not found: UpperCAmelCase : List[Any] = 0 while i < len(__magic_name__ ): if best_solution[i] != solution[i]: UpperCAmelCase : int = best_solution[i] UpperCAmelCase : Optional[int] = solution[i] break UpperCAmelCase : List[str] = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) UpperCAmelCase : List[str] = True UpperCAmelCase : List[Any] = best_solution[:-1] UpperCAmelCase : str = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: UpperCAmelCase : Union[str, Any] = cost UpperCAmelCase : Tuple = solution else: UpperCAmelCase : Optional[Any] = index_of_best_solution + 1 UpperCAmelCase : str = neighborhood[index_of_best_solution] if len(__magic_name__ ) >= size: tabu_list.pop(0 ) UpperCAmelCase : int = count + 1 return best_solution_ever, best_cost def lowercase ( __magic_name__=None ): '''simple docstring''' UpperCAmelCase : Dict = generate_neighbours(args.File ) UpperCAmelCase , UpperCAmelCase : Any = generate_first_solution( args.File , __magic_name__ ) UpperCAmelCase , UpperCAmelCase : Any = tabu_search( __magic_name__ , __magic_name__ , __magic_name__ , args.Iterations , args.Size , ) print(F"Best solution: {best_sol}, with total distance: {best_cost}." ) if __name__ == "__main__": a : Union[str, Any] = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
311
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __A ( _lowercase=None ): '''simple docstring''' if subparsers is not None: _A = subparsers.add_parser('''test''' ) else: _A = argparse.ArgumentParser('''Accelerate test command''' ) parser.add_argument( '''--config_file''' , default=_lowercase , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=_lowercase ) return parser def __A ( _lowercase ): '''simple docstring''' _A = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] ) if args.config_file is None: _A = script_name else: _A = f"""--config_file={args.config_file} {script_name}""" _A = ['''accelerate-launch'''] + test_args.split() _A = execute_subprocess_async(_lowercase , env=os.environ.copy() ) if result.returncode == 0: print('''Test is a success! You are ready for your distributed training!''' ) def __A ( ): '''simple docstring''' _A = test_command_parser() _A = parser.parse_args() test_command(_lowercase ) if __name__ == "__main__": main()
75
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @property def __A ( self: Dict ) -> Union[str, Any]: torch.manual_seed(0 ) _A = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def __A ( self: Any ) -> Union[str, Any]: _A = self.dummy_uncond_unet _A = ScoreSdeVeScheduler() _A = ScoreSdeVePipeline(unet=__A , scheduler=__A ) sde_ve.to(__A ) sde_ve.set_progress_bar_config(disable=__A ) _A = torch.manual_seed(0 ) _A = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=__A ).images _A = torch.manual_seed(0 ) _A = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=__A , return_dict=__A )[ 0 ] _A = image[0, -3:, -3:, -1] _A = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _A = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __A ( self: Dict ) -> Any: _A = '''google/ncsnpp-church-256''' _A = UNetaDModel.from_pretrained(__A ) _A = ScoreSdeVeScheduler.from_pretrained(__A ) _A = ScoreSdeVePipeline(unet=__A , scheduler=__A ) sde_ve.to(__A ) sde_ve.set_progress_bar_config(disable=__A ) _A = torch.manual_seed(0 ) _A = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=__A ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) _A = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
75
1
from scipy.stats import pearsonr import datasets _lowerCAmelCase : Optional[int] = ''' Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. ''' _lowerCAmelCase : Tuple = ''' Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric("pearsonr") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results[\'pearsonr\'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric("pearsonr") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) [\'p-value\', \'pearsonr\'] >>> print(round(results[\'pearsonr\'], 2)) -0.74 >>> print(round(results[\'p-value\'], 2)) 0.15 ''' _lowerCAmelCase : List[Any] = ''' @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("float" ), "references": datasets.Value("float" ), } ) , reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"] , ) def SCREAMING_SNAKE_CASE ( self :Dict , snake_case :Optional[Any] , snake_case :List[str] , snake_case :Union[str, Any]=False ): '''simple docstring''' if return_pvalue: A_ : Optional[Any] = pearsonr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] )}
300
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType __UpperCAmelCase = None __UpperCAmelCase = '''<''' if sys.byteorder == '''little''' else '''>''' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image __UpperCAmelCase = [ np.dtype('''|b1'''), np.dtype('''|u1'''), np.dtype('''<u2'''), np.dtype('''>u2'''), np.dtype('''<i2'''), np.dtype('''>i2'''), np.dtype('''<u4'''), np.dtype('''>u4'''), np.dtype('''<i4'''), np.dtype('''>i4'''), np.dtype('''<f4'''), np.dtype('''>f4'''), np.dtype('''<f8'''), np.dtype('''>f8'''), ] @dataclass class lowerCAmelCase_ : UpperCAmelCase__ : bool = True UpperCAmelCase__ : Optional[str] = None # Automatically constructed UpperCAmelCase__ : ClassVar[str] = "PIL.Image.Image" UpperCAmelCase__ : ClassVar[Any] = pa.struct({"bytes": pa.binary(), "path": pa.string()} ) UpperCAmelCase__ : str = field(default="Image" , init=a__ , repr=a__ ) def __call__( self ) -> Any: return self.pa_type def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = np.array(SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): return {"path": value, "bytes": None} elif isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): return {"path": None, "bytes": value} elif isinstance(SCREAMING_SNAKE_CASE_, np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(SCREAMING_SNAKE_CASE_ ) elif isinstance(SCREAMING_SNAKE_CASE_, PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(SCREAMING_SNAKE_CASE_ ) elif value.get('path' ) is not None and os.path.isfile(value['path'] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get('path' )} elif value.get('bytes' ) is not None or value.get('path' ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('bytes' ), "path": value.get('path' )} else: raise ValueError( F"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError('Decoding is disabled for this feature. Please use Image(decode=True) instead.' ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support decoding images, please install \'Pillow\'.' ) if token_per_repo_id is None: UpperCamelCase : Any = {} UpperCamelCase , UpperCamelCase : Union[str, Any] = value['path'], value['bytes'] if bytes_ is None: if path is None: raise ValueError(F"""An image should have one of 'path' or 'bytes' but both are None in {value}.""" ) else: if is_local_path(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = PIL.Image.open(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : int = path.split('::' )[-1] try: UpperCamelCase : Optional[Any] = string_to_dict(SCREAMING_SNAKE_CASE_, config.HUB_DATASETS_URL )['repo_id'] UpperCamelCase : str = token_per_repo_id.get(SCREAMING_SNAKE_CASE_ ) except ValueError: UpperCamelCase : Tuple = None with xopen(SCREAMING_SNAKE_CASE_, 'rb', use_auth_token=SCREAMING_SNAKE_CASE_ ) as f: UpperCamelCase : Optional[int] = BytesIO(f.read() ) UpperCamelCase : int = PIL.Image.open(bytes_ ) else: UpperCamelCase : Optional[int] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case_ ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value('binary' ), "path": Value('string' ), } ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> pa.StructArray: if pa.types.is_string(storage.type ): UpperCamelCase : List[str] = pa.array([None] * len(SCREAMING_SNAKE_CASE_ ), type=pa.binary() ) UpperCamelCase : Dict = pa.StructArray.from_arrays([bytes_array, storage], ['bytes', 'path'], mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCamelCase : Optional[int] = pa.array([None] * len(SCREAMING_SNAKE_CASE_ ), type=pa.string() ) UpperCamelCase : Union[str, Any] = pa.StructArray.from_arrays([storage, path_array], ['bytes', 'path'], mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('bytes' ) >= 0: UpperCamelCase : List[str] = storage.field('bytes' ) else: UpperCamelCase : List[str] = pa.array([None] * len(SCREAMING_SNAKE_CASE_ ), type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: UpperCamelCase : List[str] = storage.field('path' ) else: UpperCamelCase : Optional[Any] = pa.array([None] * len(SCREAMING_SNAKE_CASE_ ), type=pa.string() ) UpperCamelCase : Optional[int] = pa.StructArray.from_arrays([bytes_array, path_array], ['bytes', 'path'], mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCamelCase : Optional[Any] = pa.array( [encode_np_array(np.array(SCREAMING_SNAKE_CASE_ ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()], type=pa.binary(), ) UpperCamelCase : List[str] = pa.array([None] * len(SCREAMING_SNAKE_CASE_ ), type=pa.string() ) UpperCamelCase : int = pa.StructArray.from_arrays( [bytes_array, path_array], ['bytes', 'path'], mask=bytes_array.is_null() ) return array_cast(SCREAMING_SNAKE_CASE_, self.pa_type ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(SCREAMING_SNAKE_CASE_ ): with xopen(SCREAMING_SNAKE_CASE_, 'rb' ) as f: UpperCamelCase : Optional[int] = f.read() return bytes_ UpperCamelCase : Union[str, Any] = pa.array( [ (path_to_bytes(x['path'] ) if x['bytes'] is None else x['bytes']) if x is not None else None for x in storage.to_pylist() ], type=pa.binary(), ) UpperCamelCase : Any = pa.array( [os.path.basename(SCREAMING_SNAKE_CASE_ ) if path is not None else None for path in storage.field('path' ).to_pylist()], type=pa.string(), ) UpperCamelCase : int = pa.StructArray.from_arrays([bytes_array, path_array], ['bytes', 'path'], mask=bytes_array.is_null() ) return array_cast(SCREAMING_SNAKE_CASE_, self.pa_type ) def UpperCamelCase ( ) -> List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCamelCase : Dict = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def UpperCamelCase ( snake_case__ : "PIL.Image.Image" ) -> bytes: UpperCamelCase : Any = BytesIO() if image.format in list_image_compression_formats(): UpperCamelCase : Tuple = image.format else: UpperCamelCase : List[str] = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF' image.save(snake_case__ , format=snake_case__ ) return buffer.getvalue() def UpperCamelCase ( snake_case__ : "PIL.Image.Image" ) -> dict: if hasattr(snake_case__ , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(snake_case__ )} def UpperCamelCase ( snake_case__ : np.ndarray ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) UpperCamelCase : Union[str, Any] = array.dtype UpperCamelCase : List[Any] = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER UpperCamelCase : Optional[Any] = dtype.kind UpperCamelCase : Any = dtype.itemsize UpperCamelCase : int = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCamelCase : Optional[Any] = np.dtype('|u1' ) if dtype_kind not in ["u", "i"]: raise TypeError( F"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.""" ) if dtype is not dest_dtype: warnings.warn(F"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCamelCase : List[Any] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCamelCase : Dict = dtype_byteorder + dtype_kind + str(snake_case__ ) UpperCamelCase : str = np.dtype(snake_case__ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}""" ) UpperCamelCase : Union[str, Any] = PIL.Image.fromarray(array.astype(snake_case__ ) ) return {"path": None, "bytes": image_to_bytes(snake_case__ )} def UpperCamelCase ( snake_case__ : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: UpperCamelCase , UpperCamelCase : Union[str, Any] = first_non_null_value(snake_case__ ) if isinstance(snake_case__ , snake_case__ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(snake_case__ , np.ndarray ): UpperCamelCase : List[Any] = no_op_if_value_is_null(snake_case__ ) return [obj_to_image_dict_func(snake_case__ ) for obj in objs] elif isinstance(snake_case__ , PIL.Image.Image ): UpperCamelCase : Optional[int] = no_op_if_value_is_null(snake_case__ ) return [obj_to_image_dict_func(snake_case__ ) for obj in objs] else: return objs else: return objs
119
0
class SCREAMING_SNAKE_CASE__ : def __init__( self,__lowerCamelCase = "",__lowerCamelCase = False ): # Mapping from the first character of the prefix of the node A__ = {} # A node will be a leaf if the tree contains its word A__ = is_leaf A__ = prefix def UpperCamelCase ( self,__lowerCamelCase ): A__ = 0 for q, w in zip(self.prefix,__lowerCamelCase ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def UpperCamelCase ( self,__lowerCamelCase ): for word in words: self.insert(__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase ): # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: A__ = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: A__ = RadixNode(prefix=__lowerCamelCase,is_leaf=__lowerCamelCase ) else: A__ = self.nodes[word[0]] A__ , A__ , A__ = incoming_node.match( __lowerCamelCase ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(__lowerCamelCase ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: A__ = remaining_prefix A__ = self.nodes[matching_string[0]] A__ = RadixNode(__lowerCamelCase,__lowerCamelCase ) A__ = aux_node if remaining_word == "": A__ = True else: self.nodes[matching_string[0]].insert(__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase ): A__ = self.nodes.get(word[0],__lowerCamelCase ) if not incoming_node: return False else: A__ , A__ , A__ = incoming_node.match( __lowerCamelCase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase ): A__ = self.nodes.get(word[0],__lowerCamelCase ) if not incoming_node: return False else: A__ , A__ , A__ = incoming_node.match( __lowerCamelCase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(__lowerCamelCase ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: A__ = list(self.nodes.values() )[0] A__ = merging_node.is_leaf self.prefix += merging_node.prefix A__ = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: A__ = False # If there is 1 edge, we merge it with its child else: A__ = list(incoming_node.nodes.values() )[0] A__ = merging_node.is_leaf incoming_node.prefix += merging_node.prefix A__ = merging_node.nodes return True def UpperCamelCase ( self,__lowerCamelCase = 0 ): if self.prefix != "": print('''-''' * height,self.prefix,''' (leaf)''' if self.is_leaf else '''''' ) for value in self.nodes.values(): value.print_tree(height + 1 ) def UpperCamelCase__( )->bool: A__ = '''banana bananas bandana band apple all beast'''.split() A__ = RadixNode() root.insert_many(UpperCamelCase__ ) assert all(root.find(UpperCamelCase__ ) for word in words ) assert not root.find('''bandanas''' ) assert not root.find('''apps''' ) root.delete('''all''' ) assert not root.find('''all''' ) root.delete('''banana''' ) assert not root.find('''banana''' ) assert root.find('''bananas''' ) return True def UpperCamelCase__( )->None: assert test_trie() def UpperCamelCase__( )->None: A__ = RadixNode() A__ = '''banana bananas bandanas bandana band apple all beast'''.split() root.insert_many(UpperCamelCase__ ) print('''Words:''' , UpperCamelCase__ ) print('''Tree:''' ) root.print_tree() if __name__ == "__main__": main()
366
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a__: List[Any] = logging.get_logger(__name__) a__: Optional[Any] = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = '''unispeech''' def __init__( self,__lowerCamelCase=32,__lowerCamelCase=768,__lowerCamelCase=12,__lowerCamelCase=12,__lowerCamelCase=3072,__lowerCamelCase="gelu",__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=0.0,__lowerCamelCase=0.0,__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=0.02,__lowerCamelCase=1E-5,__lowerCamelCase="group",__lowerCamelCase="gelu",__lowerCamelCase=(512, 512, 512, 512, 512, 512, 512),__lowerCamelCase=(5, 2, 2, 2, 2, 2, 2),__lowerCamelCase=(10, 3, 3, 3, 3, 2, 2),__lowerCamelCase=False,__lowerCamelCase=128,__lowerCamelCase=16,__lowerCamelCase=False,__lowerCamelCase=True,__lowerCamelCase=0.05,__lowerCamelCase=10,__lowerCamelCase=2,__lowerCamelCase=0.0,__lowerCamelCase=10,__lowerCamelCase=0,__lowerCamelCase=320,__lowerCamelCase=2,__lowerCamelCase=0.1,__lowerCamelCase=100,__lowerCamelCase=256,__lowerCamelCase=256,__lowerCamelCase=0.1,__lowerCamelCase="mean",__lowerCamelCase=False,__lowerCamelCase=False,__lowerCamelCase=256,__lowerCamelCase=80,__lowerCamelCase=0,__lowerCamelCase=1,__lowerCamelCase=2,__lowerCamelCase=0.5,**__lowerCamelCase,): super().__init__(**__lowerCamelCase,pad_token_id=__lowerCamelCase,bos_token_id=__lowerCamelCase,eos_token_id=__lowerCamelCase ) A__ = hidden_size A__ = feat_extract_norm A__ = feat_extract_activation A__ = list(__lowerCamelCase ) A__ = list(__lowerCamelCase ) A__ = list(__lowerCamelCase ) A__ = conv_bias A__ = num_conv_pos_embeddings A__ = num_conv_pos_embedding_groups A__ = len(self.conv_dim ) A__ = num_hidden_layers A__ = intermediate_size A__ = hidden_act A__ = num_attention_heads A__ = hidden_dropout A__ = attention_dropout A__ = activation_dropout A__ = feat_proj_dropout A__ = final_dropout A__ = layerdrop A__ = layer_norm_eps A__ = initializer_range A__ = num_ctc_classes A__ = vocab_size A__ = do_stable_layer_norm A__ = use_weighted_layer_sum A__ = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`," f" `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A__ = apply_spec_augment A__ = mask_time_prob A__ = mask_time_length A__ = mask_time_min_masks A__ = mask_feature_prob A__ = mask_feature_length A__ = mask_feature_min_masks # parameters for pretraining with codevector quantized representations A__ = num_codevectors_per_group A__ = num_codevector_groups A__ = contrastive_logits_temperature A__ = feat_quantizer_dropout A__ = num_negatives A__ = codevector_dim A__ = proj_codevector_dim A__ = diversity_loss_weight # ctc loss A__ = ctc_loss_reduction A__ = ctc_zero_infinity # pretraining loss A__ = replace_prob @property def UpperCamelCase ( self ): return functools.reduce(operator.mul,self.conv_stride,1 )
39
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __snake_case = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def a ( __a ) -> Optional[Any]: '''simple docstring''' if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): UpperCamelCase__ :Any = [image] UpperCamelCase__ :Any = [trans(img.convert('''RGB''' ) ) for img in image] UpperCamelCase__ :List[str] = torch.stack(__a ) return image class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase__ :str = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=UpperCamelCase_ , scheduler=UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[str] = min(int(num_inference_steps * strength ) , UpperCamelCase_ ) UpperCamelCase__ :List[str] = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase__ :Dict = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None ): '''simple docstring''' if not isinstance(UpperCamelCase_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCamelCase_ )}''' ) UpperCamelCase__ :List[str] = image.to(device=UpperCamelCase_ , dtype=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) and len(UpperCamelCase_ ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(UpperCamelCase_ )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase__ :List[Any] = init_latents.shape UpperCamelCase__ :int = randn_tensor(UpperCamelCase_ , generator=UpperCamelCase_ , device=UpperCamelCase_ , dtype=UpperCamelCase_ ) # get latents print('''add noise to latents at timestep''' , UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = self.scheduler.add_noise(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase__ :Any = init_latents return latents @torch.no_grad() def __call__( self , UpperCamelCase_ = None , UpperCamelCase_ = 0.8 , UpperCamelCase_ = 1 , UpperCamelCase_ = None , UpperCamelCase_ = 0.0 , UpperCamelCase_ = 50 , UpperCamelCase_ = None , UpperCamelCase_ = "pil" , UpperCamelCase_ = True , ): '''simple docstring''' self.check_inputs(UpperCamelCase_ ) # 2. Preprocess image UpperCamelCase__ :Tuple = preprocess(UpperCamelCase_ ) # 3. set timesteps self.scheduler.set_timesteps(UpperCamelCase_ , device=self.device ) UpperCamelCase__ , UpperCamelCase__ :Tuple = self.get_timesteps(UpperCamelCase_ , UpperCamelCase_ , self.device ) UpperCamelCase__ :Tuple = timesteps[:1].repeat(UpperCamelCase_ ) # 4. Prepare latent variables UpperCamelCase__ :int = self.prepare_latents(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , self.unet.dtype , self.device , UpperCamelCase_ ) UpperCamelCase__ :int = latents # 5. Denoising loop for t in self.progress_bar(UpperCamelCase_ ): # 1. predict noise model_output UpperCamelCase__ :Optional[Any] = self.unet(UpperCamelCase_ , UpperCamelCase_ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase__ :Dict = self.scheduler.step( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , eta=UpperCamelCase_ , use_clipped_model_output=UpperCamelCase_ , generator=UpperCamelCase_ , ).prev_sample UpperCamelCase__ :Dict = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ :Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ :Dict = self.numpy_to_pil(UpperCamelCase_ ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCamelCase_ )
97
'''simple docstring''' from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _A : List[Any] = 299792458 # Symbols _A , _A , _A , _A : Union[str, Any] = symbols('''ct x y z''') def UpperCamelCase_ ( snake_case_ : float ) -> float: '''simple docstring''' if velocity > c: raise ValueError("""Speed must not exceed light speed 299,792,458 [m/s]!""" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("""Speed must be greater than or equal to 1!""" ) return velocity / c def UpperCamelCase_ ( snake_case_ : float ) -> float: '''simple docstring''' return 1 / sqrt(1 - beta(snake_case_ ) ** 2 ) def UpperCamelCase_ ( snake_case_ : float ) -> np.ndarray: '''simple docstring''' return np.array( [ [gamma(snake_case_ ), -gamma(snake_case_ ) * beta(snake_case_ ), 0, 0], [-gamma(snake_case_ ) * beta(snake_case_ ), gamma(snake_case_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def UpperCamelCase_ ( snake_case_ : float , snake_case_ : np.ndarray | None = None ) -> np.ndarray: '''simple docstring''' if event is None: __lowerCAmelCase = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(snake_case_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _A : str = transform(29979245) print('''Example of four vector: ''') print(f'ct\' = {four_vector[0]}') print(f'x\' = {four_vector[1]}') print(f'y\' = {four_vector[2]}') print(f'z\' = {four_vector[3]}') # Substitute symbols with numerical values _A : int = {ct: c, x: 1, y: 1, z: 1} _A : Any = [four_vector[i].subs(sub_dict) for i in range(4)] print(f'\n{numerical_vector}')
229
0
def UpperCamelCase (lowercase_: int = 3 , lowercase_: int = 7 , lowercase_: int = 1000000 ) -> int: A__ : str = 0 A__ : str = 1 for current_denominator in range(1 , limit + 1 ): A__ : List[Any] = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: A__ : Any = current_numerator A__ : Dict = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=100_0000))
141
from __future__ import annotations def UpperCamelCase (lowercase_: float , lowercase_: float , lowercase_: float ) -> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
141
1
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast __A =datasets.utils.logging.get_logger(__name__) @dataclass class _SCREAMING_SNAKE_CASE ( datasets.BuilderConfig ): lowerCAmelCase__ = 1_00_00 lowerCAmelCase__ = None lowerCAmelCase__ = None class _SCREAMING_SNAKE_CASE ( datasets.ArrowBasedBuilder ): lowerCAmelCase__ = ParquetConfig def SCREAMING_SNAKE_CASE_( self ) -> Any: return datasets.DatasetInfo(features=self.config.features ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Tuple: if not self.config.data_files: raise ValueError(f'At least one data file must be specified, but got data_files={self.config.data_files}' ) lowerCamelCase_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(lowercase , (str, list, tuple) ): lowerCamelCase_ = data_files if isinstance(lowercase , lowercase ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(lowercase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] lowerCamelCase_ = [] for split_name, files in data_files.items(): if isinstance(lowercase , lowercase ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(lowercase ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(lowercase ): with open(lowercase , "rb" ) as f: lowerCamelCase_ = datasets.Features.from_arrow_schema(pq.read_schema(lowercase ) ) break splits.append(datasets.SplitGenerator(name=lowercase , gen_kwargs={"files": files} ) ) return splits def SCREAMING_SNAKE_CASE_( self , lowercase ) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowerCamelCase_ = table_cast(lowercase , self.info.features.arrow_schema ) return pa_table def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Dict: lowerCamelCase_ = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( f'Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'' ) for file_idx, file in enumerate(itertools.chain.from_iterable(lowercase ) ): with open(lowercase , "rb" ) as f: lowerCamelCase_ = pq.ParquetFile(lowercase ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): lowerCamelCase_ = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f'{file_idx}_{batch_idx}', self._cast_table(lowercase ) except ValueError as e: logger.error(f'Failed to read file \'{file}\' with error {type(lowercase )}: {e}' ) raise
19
from abc import ABC, abstractmethod from argparse import ArgumentParser class _SCREAMING_SNAKE_CASE ( snake_case_ ): @staticmethod @abstractmethod def SCREAMING_SNAKE_CASE_( lowercase ) -> int: raise NotImplementedError() @abstractmethod def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: raise NotImplementedError()
19
1
from __future__ import annotations def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> list[list[int]]: '''simple docstring''' UpperCAmelCase : list[list[int]] =[] create_all_state(1 , __lowerCAmelCase , __lowerCAmelCase , [] , __lowerCAmelCase ) return result def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , )-> None: '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(__lowerCAmelCase , total_number - level + 2 ): current_list.append(__lowerCAmelCase ) create_all_state(i + 1 , __lowerCAmelCase , level - 1 , __lowerCAmelCase , __lowerCAmelCase ) current_list.pop() def lowerCAmelCase_ ( __lowerCAmelCase )-> None: '''simple docstring''' for i in total_list: print(*__lowerCAmelCase ) if __name__ == "__main__": __snake_case = 4 __snake_case = 2 __snake_case = generate_all_combinations(n, k) print_all_state(total_list)
363
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __snake_case ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase : List[Any] = KandinskyVaaControlnetPipeline __lowerCamelCase : int = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowerCamelCase : Optional[int] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowerCamelCase : Optional[Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowerCamelCase : Dict = False @property def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return 32 @property def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' return 32 @property def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' return self.time_input_dim @property def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' return self.time_input_dim * 4 @property def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return 100 @property def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Any ={ '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } UpperCAmelCase : List[Any] =UNetaDConditionModel(**snake_case__ ) return model @property def UpperCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def UpperCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Any =VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : List[str] =self.dummy_unet UpperCAmelCase : Tuple =self.dummy_movq UpperCAmelCase : Union[str, Any] =DDIMScheduler( num_train_timesteps=1000 , beta_schedule='''linear''' , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=snake_case__ , set_alpha_to_one=snake_case__ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=snake_case__ , ) UpperCAmelCase : Tuple ={ '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def UpperCAmelCase__ ( self , snake_case__ , snake_case__=0 ) -> Any: '''simple docstring''' UpperCAmelCase : str =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) UpperCAmelCase : Tuple =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( snake_case__ ) # create hint UpperCAmelCase : Tuple =floats_tensor((1, 3, 64, 64) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) if str(snake_case__ ).startswith('''mps''' ): UpperCAmelCase : Optional[int] =torch.manual_seed(snake_case__ ) else: UpperCAmelCase : int =torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) UpperCAmelCase : List[str] ={ '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' UpperCAmelCase : List[Any] ='''cpu''' UpperCAmelCase : List[Any] =self.get_dummy_components() UpperCAmelCase : Tuple =self.pipeline_class(**snake_case__ ) UpperCAmelCase : Tuple =pipe.to(snake_case__ ) pipe.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase : Optional[int] =pipe(**self.get_dummy_inputs(snake_case__ ) ) UpperCAmelCase : str =output.images UpperCAmelCase : List[str] =pipe( **self.get_dummy_inputs(snake_case__ ) , return_dict=snake_case__ , )[0] UpperCAmelCase : Union[str, Any] =image[0, -3:, -3:, -1] UpperCAmelCase : List[str] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : Union[str, Any] =np.array( [0.695_9826, 0.86_8279, 0.755_8092, 0.6876_9467, 0.8580_5804, 0.6597_7496, 0.4488_5302, 0.595_9111, 0.425_1595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : Union[str, Any] =load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy''' ) UpperCAmelCase : Tuple =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) UpperCAmelCase : int =torch.from_numpy(np.array(snake_case__ ) ).float() / 255.0 UpperCAmelCase : List[str] =hint.permute(2 , 0 , 1 ).unsqueeze(0 ) UpperCAmelCase : Dict =KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(snake_case__ ) UpperCAmelCase : int =KandinskyVaaControlnetPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) UpperCAmelCase : str =pipeline.to(snake_case__ ) pipeline.set_progress_bar_config(disable=snake_case__ ) UpperCAmelCase : int ='''A robot, 4k photo''' UpperCAmelCase : int =torch.Generator(device='''cuda''' ).manual_seed(0 ) UpperCAmelCase , UpperCAmelCase : List[str] =pipe_prior( snake_case__ , generator=snake_case__ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() UpperCAmelCase : List[str] =torch.Generator(device='''cuda''' ).manual_seed(0 ) UpperCAmelCase : Dict =pipeline( image_embeds=snake_case__ , negative_image_embeds=snake_case__ , hint=snake_case__ , generator=snake_case__ , num_inference_steps=100 , output_type='''np''' , ) UpperCAmelCase : List[Any] =output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(snake_case__ , snake_case__ )
78
0
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
58
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
1
"""simple docstring""" import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: A__ = model.config A__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) A__ = MBartConfig( is_decoder=lowercase_ , is_encoder_decoder=lowercase_ , add_cross_attention=lowercase_ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=lowercase_ , add_final_layer_norm=lowercase_ , ) return encoder_config, decoder_config def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: if "encoder.model" in name: A__ = name.replace("encoder.model" , "encoder" ) if "decoder.model" in name: A__ = name.replace("decoder.model" , "decoder" ) if "patch_embed.proj" in name: A__ = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: A__ = name.replace("patch_embed.norm" , "embeddings.norm" ) if name.startswith("encoder" ): if "layers" in name: A__ = "encoder." + name if "attn.proj" in name: A__ = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name and "mask" not in name: A__ = name.replace("attn" , "attention.self" ) if "norm1" in name: A__ = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: A__ = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: A__ = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: A__ = name.replace("mlp.fc2" , "output.dense" ) if name == "encoder.norm.weight": A__ = "encoder.layernorm.weight" if name == "encoder.norm.bias": A__ = "encoder.layernorm.bias" return name def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Any: for key in orig_state_dict.copy().keys(): A__ = orig_state_dict.pop(lowercase_ ) if "qkv" in key: A__ = key.split("." ) A__ = int(key_split[3] ) A__ = int(key_split[5] ) A__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A__ = val[:dim, :] A__ = val[dim : dim * 2, :] A__ = val[-dim:, :] else: A__ = val[:dim] A__ = val[dim : dim * 2] A__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: A__ = val return orig_state_dict def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=False ) -> Dict: # load original model A__ = DonutModel.from_pretrained(lowercase_ ).eval() # load HuggingFace model A__, A__ = get_configs(lowercase_ ) A__ = DonutSwinModel(lowercase_ ) A__ = MBartForCausalLM(lowercase_ ) A__ = VisionEncoderDecoderModel(encoder=lowercase_ , decoder=lowercase_ ) model.eval() A__ = original_model.state_dict() A__ = convert_state_dict(lowercase_ , lowercase_ ) model.load_state_dict(lowercase_ ) # verify results on scanned document A__ = load_dataset("hf-internal-testing/example-documents" ) A__ = dataset["test"][0]["image"].convert("RGB" ) A__ = XLMRobertaTokenizerFast.from_pretrained(lowercase_ , from_slow=lowercase_ ) A__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) A__ = DonutProcessor(lowercase_ , lowercase_ ) A__ = processor(lowercase_ , return_tensors="pt" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": A__ = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" A__ = "When is the coffee break?" A__ = task_prompt.replace("{user_input}" , lowercase_ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": A__ = "<s_rvlcdip>" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: A__ = "<s_cord>" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": A__ = "s_cord-v2>" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": A__ = "<s_zhtrainticket>" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt A__ = "hello world" else: raise ValueError("Model name not supported" ) A__ = original_model.decoder.tokenizer(lowercase_ , add_special_tokens=lowercase_ , return_tensors="pt" )[ "input_ids" ] A__ = original_model.encoder.model.patch_embed(lowercase_ ) A__, A__ = model.encoder.embeddings(lowercase_ ) assert torch.allclose(lowercase_ , lowercase_ , atol=1E-3 ) # verify encoder hidden states A__ = original_model.encoder(lowercase_ ) A__ = model.encoder(lowercase_ ).last_hidden_state assert torch.allclose(lowercase_ , lowercase_ , atol=1E-2 ) # verify decoder hidden states A__ = original_model(lowercase_ , lowercase_ , lowercase_ ).logits A__ = model(lowercase_ , decoder_input_ids=lowercase_ ).logits assert torch.allclose(lowercase_ , lowercase_ , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if push_to_hub: model.push_to_hub("nielsr/" + model_name.split("/" )[-1] , commit_message="Update model" ) processor.push_to_hub("nielsr/" + model_name.split("/" )[-1] , commit_message="Update model" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, 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 and processor to the 🤗 hub.", ) SCREAMING_SNAKE_CASE = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
230
"""simple docstring""" SCREAMING_SNAKE_CASE = "Alexander Joslin" import operator as op from .stack import Stack def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: A__ = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} A__ = Stack() A__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(lowercase_ ) ) elif i in operators: # RULE 2 operator_stack.push(lowercase_ ) elif i == ")": # RULE 4 A__ = operator_stack.peek() operator_stack.pop() A__ = operand_stack.peek() operand_stack.pop() A__ = operand_stack.peek() operand_stack.pop() A__ = operators[opr](lowercase_ , lowercase_ ) operand_stack.push(lowercase_ ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": SCREAMING_SNAKE_CASE = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')
230
1
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
"""simple docstring""" 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 A_ ( _lowercase, _lowercase ): '''simple docstring''' snake_case_ :int = XCLIPTextConfig() # derive patch size from model name snake_case_ :Union[str, Any] = model_name.find("""patch""" ) snake_case_ :List[str] = int(model_name[start_idx + len("""patch""" ) : start_idx + len("""patch""" ) + 2] ) snake_case_ :Any = XCLIPVisionConfig(patch_size=_lowercase, num_frames=_lowercase ) if "large" in model_name: snake_case_ :Optional[Any] = 768 snake_case_ :Union[str, Any] = 3072 snake_case_ :Any = 12 snake_case_ :Any = 1024 snake_case_ :str = 4096 snake_case_ :Union[str, Any] = 16 snake_case_ :Union[str, Any] = 24 snake_case_ :Tuple = 768 snake_case_ :Any = 3072 if model_name == "xclip-large-patch14-16-frames": snake_case_ :Any = 336 snake_case_ :Any = XCLIPConfig.from_text_vision_configs(_lowercase, _lowercase ) if "large" in model_name: snake_case_ :List[Any] = 768 return config def A_ ( _lowercase ): '''simple docstring''' if name == "token_embedding.weight": snake_case_ :Optional[Any] = name.replace("""token_embedding.weight""", """text_model.embeddings.token_embedding.weight""" ) if name == "positional_embedding": snake_case_ :Tuple = name.replace("""positional_embedding""", """text_model.embeddings.position_embedding.weight""" ) if "ln_1" in name: snake_case_ :Dict = name.replace("""ln_1""", """layer_norm1""" ) if "ln_2" in name: snake_case_ :str = name.replace("""ln_2""", """layer_norm2""" ) if "c_fc" in name: snake_case_ :str = name.replace("""c_fc""", """fc1""" ) if "c_proj" in name: snake_case_ :int = name.replace("""c_proj""", """fc2""" ) if name.startswith("""transformer.resblocks""" ): snake_case_ :Union[str, Any] = name.replace("""transformer.resblocks""", """text_model.encoder.layers""" ) if "attn.out_proj" in name and "message" not in name: snake_case_ :Union[str, Any] = name.replace("""attn.out_proj""", """self_attn.out_proj""" ) if "ln_final" in name: snake_case_ :Union[str, Any] = name.replace("""ln_final""", """text_model.final_layer_norm""" ) # visual encoder if name == "visual.class_embedding": snake_case_ :Any = name.replace("""visual.class_embedding""", """vision_model.embeddings.class_embedding""" ) if name == "visual.positional_embedding": snake_case_ :Optional[int] = name.replace("""visual.positional_embedding""", """vision_model.embeddings.position_embedding.weight""" ) if name.startswith("""visual.transformer.resblocks""" ): snake_case_ :Union[str, Any] = name.replace("""visual.transformer.resblocks""", """vision_model.encoder.layers""" ) if "visual.conv1" in name: snake_case_ :int = name.replace("""visual.conv1""", """vision_model.embeddings.patch_embedding""" ) if "visual.ln_pre" in name: snake_case_ :Any = name.replace("""visual.ln_pre""", """vision_model.pre_layernorm""" ) if "visual.ln_post" in name: snake_case_ :str = name.replace("""visual.ln_post""", """vision_model.post_layernorm""" ) if "visual.proj" in name: snake_case_ :Union[str, Any] = name.replace("""visual.proj""", """visual_projection.weight""" ) if "text_projection" in name: snake_case_ :Dict = name.replace("""text_projection""", """text_projection.weight""" ) # things on top if "prompts_visual_proj" in name: snake_case_ :List[str] = name.replace("""prompts_visual_proj""", """prompts_visual_projection""" ) if "prompts_visual_ln" in name: snake_case_ :Dict = name.replace("""prompts_visual_ln""", """prompts_visual_layernorm""" ) # mit if name == "mit.positional_embedding": snake_case_ :str = name.replace("""positional""", """position""" ) if name.startswith("""mit.resblocks""" ): snake_case_ :Dict = name.replace("""mit.resblocks""", """mit.encoder.layers""" ) # prompts generator if name.startswith("""prompts_generator.norm""" ): snake_case_ :Union[str, Any] = name.replace("""prompts_generator.norm""", """prompts_generator.layernorm""" ) return name def A_ ( _lowercase, _lowercase ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case_ :Dict = orig_state_dict.pop(_lowercase ) if "attn.in_proj" in key: snake_case_ :Optional[Any] = key.split(""".""" ) if key.startswith("""visual""" ): snake_case_ :Any = key_split[3] snake_case_ :Optional[Any] = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: snake_case_ :str = val[ :dim, : ] snake_case_ :Optional[int] = val[ dim : dim * 2, : ] snake_case_ :Union[str, Any] = val[ -dim:, : ] else: snake_case_ :Dict = val[ :dim ] snake_case_ :Optional[int] = val[ dim : dim * 2 ] snake_case_ :Optional[int] = val[ -dim: ] else: if "weight" in key: snake_case_ :Optional[Any] = val[ :dim, : ] snake_case_ :List[str] = val[ dim : dim * 2, : ] snake_case_ :Dict = val[ -dim:, : ] else: snake_case_ :Union[str, Any] = val[:dim] snake_case_ :Union[str, Any] = val[ dim : dim * 2 ] snake_case_ :Union[str, Any] = val[-dim:] elif key.startswith("""mit""" ): snake_case_ :Tuple = key_split[2] snake_case_ :Union[str, Any] = config.vision_config.mit_hidden_size if "weight" in key: snake_case_ :Optional[int] = val[:dim, :] snake_case_ :Optional[int] = val[dim : dim * 2, :] snake_case_ :str = val[-dim:, :] else: snake_case_ :str = val[:dim] snake_case_ :Any = val[dim : dim * 2] snake_case_ :int = val[-dim:] else: snake_case_ :Tuple = key_split[2] snake_case_ :Any = config.text_config.hidden_size if "weight" in key: snake_case_ :Dict = val[:dim, :] snake_case_ :Dict = val[ dim : dim * 2, : ] snake_case_ :List[str] = val[-dim:, :] else: snake_case_ :Any = val[:dim] snake_case_ :Tuple = val[ dim : dim * 2 ] snake_case_ :List[str] = val[-dim:] else: snake_case_ :Optional[int] = rename_key(_lowercase ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: snake_case_ :Optional[Any] = val.T snake_case_ :Tuple = val return orig_state_dict def A_ ( _lowercase ): '''simple docstring''' if num_frames == 8: snake_case_ :str = """eating_spaghetti_8_frames.npy""" elif num_frames == 16: snake_case_ :int = """eating_spaghetti.npy""" elif num_frames == 32: snake_case_ :List[str] = """eating_spaghetti_32_frames.npy""" snake_case_ :int = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""", filename=_lowercase, repo_type="""dataset""", ) snake_case_ :Union[str, Any] = np.load(_lowercase ) return list(_lowercase ) def A_ ( _lowercase, _lowercase=None, _lowercase=False ): '''simple docstring''' snake_case_ :List[Any] = { # 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""", } snake_case_ :Optional[int] = model_to_url[model_name] snake_case_ :int = 8 if "16-frames" in model_name: snake_case_ :List[Any] = 16 elif "shot" in model_name: snake_case_ :Dict = 32 snake_case_ :Optional[int] = get_xclip_config(_lowercase, _lowercase ) snake_case_ :Optional[Any] = XCLIPModel(_lowercase ) model.eval() if "drive" in checkpoint_url: snake_case_ :List[str] = """pytorch_model.bin""" gdown.cached_download(_lowercase, _lowercase, quiet=_lowercase ) snake_case_ :List[Any] = torch.load(_lowercase, map_location="""cpu""" )["""model"""] else: snake_case_ :Tuple = torch.hub.load_state_dict_from_url(_lowercase )["""model"""] snake_case_ :Union[str, Any] = convert_state_dict(_lowercase, _lowercase ) snake_case_ :str = XCLIPModel(_lowercase ) snake_case_, snake_case_ :Optional[int] = model.load_state_dict(_lowercase, strict=_lowercase ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() snake_case_ :List[str] = 336 if model_name == """xclip-large-patch14-16-frames""" else 224 snake_case_ :List[Any] = VideoMAEImageProcessor(size=_lowercase ) snake_case_ :Any = CLIPTokenizer.from_pretrained("""openai/clip-vit-base-patch32""" ) snake_case_ :str = CLIPTokenizerFast.from_pretrained("""openai/clip-vit-base-patch32""" ) snake_case_ :Optional[Any] = XCLIPProcessor(image_processor=_lowercase, tokenizer=_lowercase ) snake_case_ :Optional[int] = prepare_video(_lowercase ) snake_case_ :Optional[Any] = processor( text=["""playing sports""", """eating spaghetti""", """go shopping"""], videos=_lowercase, return_tensors="""pt""", padding=_lowercase ) print("""Shape of pixel values:""", inputs.pixel_values.shape ) with torch.no_grad(): snake_case_ :List[Any] = model(**_lowercase ) # Verify outputs snake_case_ :List[Any] = outputs.logits_per_video snake_case_ :Any = logits_per_video.softmax(dim=1 ) print("""Probs:""", _lowercase ) # kinetics-400 if model_name == "xclip-base-patch32": snake_case_ :Union[str, Any] = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": snake_case_ :str = torch.tensor([[7.09_99e-04, 9.98_83e-01, 4.55_80e-04]] ) elif model_name == "xclip-base-patch16": snake_case_ :Tuple = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": snake_case_ :Any = torch.tensor([[7.69_37e-04, 9.97_28e-01, 1.94_73e-03]] ) elif model_name == "xclip-large-patch14": snake_case_ :str = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": snake_case_ :Tuple = torch.tensor([[3.38_77e-04, 9.99_37e-01, 2.88_88e-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": snake_case_ :List[Any] = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": snake_case_ :Union[str, Any] = torch.tensor([[3.85_54e-04, 9.99_29e-01, 3.27_54e-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": snake_case_ :List[Any] = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": snake_case_ :Dict = torch.tensor([[7.18_90e-06, 9.99_94e-01, 5.65_59e-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": snake_case_ :Union[str, Any] = torch.tensor([[1.03_20e-05, 9.99_93e-01, 6.24_35e-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": snake_case_ :str = torch.tensor([[4.13_77e-06, 9.99_90e-01, 9.83_86e-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": snake_case_ :str = torch.tensor([[4.13_47e-05, 9.99_62e-01, 3.34_11e-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": snake_case_ :int = torch.tensor([[8.58_57e-05, 9.99_28e-01, 6.32_91e-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": snake_case_ :Optional[int] = torch.tensor([[8.58_57e-05, 9.99_28e-01, 6.32_91e-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": snake_case_ :Any = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": snake_case_ :Tuple = torch.tensor([[9.82_19e-04, 9.95_93e-01, 3.08_63e-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": snake_case_ :Union[str, Any] = torch.tensor([[3.50_82e-04, 9.97_85e-01, 1.79_66e-03]] ) else: raise ValueError(f"""Model name {model_name} not supported""" ) assert torch.allclose(_lowercase, _lowercase, 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(_lowercase ) if push_to_hub: print("""Pushing model, processor and slow tokenizer files to the hub...""" ) model.push_to_hub(_lowercase, organization="""nielsr""" ) processor.push_to_hub(_lowercase, organization="""nielsr""" ) slow_tokenizer.push_to_hub(_lowercase, organization="""nielsr""" ) if __name__ == "__main__": __a = 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." ) __a = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
66
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__: str = logging.get_logger(__name__) a__: int = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = '''distilbert''' __SCREAMING_SNAKE_CASE = { '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self,__lowerCamelCase=3_0522,__lowerCamelCase=512,__lowerCamelCase=False,__lowerCamelCase=6,__lowerCamelCase=12,__lowerCamelCase=768,__lowerCamelCase=4 * 768,__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase="gelu",__lowerCamelCase=0.02,__lowerCamelCase=0.1,__lowerCamelCase=0.2,__lowerCamelCase=0,**__lowerCamelCase,): A__ = vocab_size A__ = max_position_embeddings A__ = sinusoidal_pos_embds A__ = n_layers A__ = n_heads A__ = dim A__ = hidden_dim A__ = dropout A__ = attention_dropout A__ = activation A__ = initializer_range A__ = qa_dropout A__ = seq_classif_dropout super().__init__(**__lowerCamelCase,pad_token_id=__lowerCamelCase ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): @property def UpperCamelCase ( self ): if self.task == "multiple-choice": A__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
358
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = None def UpperCamelCase__( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple=0.999 , UpperCamelCase__ : Optional[int]="cosine" , )->Optional[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(UpperCamelCase__ : List[str] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(UpperCamelCase__ : Union[str, Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) A__ = [] for i in range(UpperCamelCase__ ): A__ = i / num_diffusion_timesteps A__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(UpperCamelCase__ ) / alpha_bar_fn(UpperCamelCase__ ) , UpperCamelCase__ ) ) return torch.tensor(UpperCamelCase__ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = 1 @register_to_config def __init__( self,__lowerCamelCase = 1000,__lowerCamelCase = 0.0001,__lowerCamelCase = 0.02,__lowerCamelCase = "linear",__lowerCamelCase = None,__lowerCamelCase = True,__lowerCamelCase = True,__lowerCamelCase = 0,__lowerCamelCase = "epsilon",__lowerCamelCase = 1.0,**__lowerCamelCase,): if kwargs.get('''set_alpha_to_one''',__lowerCamelCase ) is not None: A__ = ( '''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.''' ) deprecate('''set_alpha_to_one''','''1.0.0''',__lowerCamelCase,standard_warn=__lowerCamelCase ) A__ = kwargs['''set_alpha_to_one'''] if trained_betas is not None: A__ = torch.tensor(__lowerCamelCase,dtype=torch.floataa ) elif beta_schedule == "linear": A__ = torch.linspace(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A__ = ( torch.linspace(beta_start**0.5,beta_end**0.5,__lowerCamelCase,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A__ = betas_for_alpha_bar(__lowerCamelCase ) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" ) A__ = 1.0 - self.betas A__ = torch.cumprod(self.alphas,dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. A__ = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution A__ = 1.0 # setable values A__ = None A__ = torch.from_numpy(np.arange(0,__lowerCamelCase ).copy().astype(np.intaa ) ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): return sample def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:" f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle" f" maximal {self.config.num_train_timesteps} timesteps." ) A__ = num_inference_steps A__ = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A__ = (np.arange(0,__lowerCamelCase ) * step_ratio).round().copy().astype(np.intaa ) A__ = torch.from_numpy(__lowerCamelCase ).to(__lowerCamelCase ) self.timesteps += self.config.steps_offset def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase = 0.0,__lowerCamelCase = False,__lowerCamelCase = None,__lowerCamelCase = True,): # 1. get previous step value (=t+1) A__ = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process A__ = self.alphas_cumprod[timestep] A__ = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) A__ = 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 if self.config.prediction_type == "epsilon": A__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 A__ = model_output elif self.config.prediction_type == "sample": A__ = model_output A__ = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": A__ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output A__ = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" ''' `v_prediction`''' ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: A__ = pred_original_sample.clamp( -self.config.clip_sample_range,self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A__ = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A__ = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=__lowerCamelCase,pred_original_sample=__lowerCamelCase ) def __len__( self ): return self.config.num_train_timesteps
39
0
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( __snake_case : list[int | str] ) -> None: create_state_space_tree(__snake_case , [] , 0 , [0 for i in range(len(__snake_case ) )] ) def _lowerCAmelCase ( __snake_case : list[int | str] , __snake_case : list[int | str] , __snake_case : int , __snake_case : list[int] , ) -> None: if index == len(__snake_case ): print(__snake_case ) return for i in range(len(__snake_case ) ): if not index_used[i]: current_sequence.append(sequence[i] ) __A : Dict = True create_state_space_tree(__snake_case , __snake_case , index + 1 , __snake_case ) current_sequence.pop() __A : int = False lowercase__ : list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) lowercase__ : list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_a)
190
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[Any] = tempfile.mkdtemp() # fmt: off __A : Optional[int] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Tuple = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase)))) __A : Any = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : List[str] = {'unk_token': '<unk>'} __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file']) with open(self.vocab_file , 'w' , encoding='utf-8') as fp: fp.write(json.dumps(_UpperCAmelCase) + '\n') with open(self.merges_file , 'w' , encoding='utf-8') as fp: fp.write('\n'.join(_UpperCAmelCase)) __A : str = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.48145466, 0.4578275, 0.40821073], 'image_std': [0.26862954, 0.26130258, 0.27577711], } __A : Union[str, Any] = os.path.join(self.tmpdirname , _UpperCAmelCase) with open(self.image_processor_file , 'w' , encoding='utf-8') as fp: json.dump(_UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , **_UpperCAmelCase): '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , **_UpperCAmelCase): '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , **_UpperCAmelCase): '''simple docstring''' return CLIPImageProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] __A : Optional[int] = [Image.fromarray(np.moveaxis(_UpperCAmelCase , 0 , -1)) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : str = self.get_tokenizer() __A : int = self.get_rust_tokenizer() __A : Any = self.get_image_processor() __A : Union[str, Any] = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) processor_slow.save_pretrained(self.tmpdirname) __A : Dict = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_UpperCAmelCase) __A : Union[str, Any] = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) processor_fast.save_pretrained(self.tmpdirname) __A : Union[str, Any] = CLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , _UpperCAmelCase) self.assertIsInstance(processor_fast.tokenizer , _UpperCAmelCase) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , _UpperCAmelCase) self.assertIsInstance(processor_fast.image_processor , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) __A : Dict = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') __A : Any = self.get_image_processor(do_normalize=_UpperCAmelCase , padding_value=1.0) __A : Tuple = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_UpperCAmelCase , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , _UpperCAmelCase) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = self.get_image_processor() __A : List[Any] = self.get_tokenizer() __A : List[Any] = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : List[str] = self.prepare_image_inputs() __A : Dict = image_processor(_UpperCAmelCase , return_tensors='np') __A : str = processor(images=_UpperCAmelCase , return_tensors='np') for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : Dict = 'lower newer' __A : List[Any] = processor(text=_UpperCAmelCase) __A : Optional[int] = tokenizer(_UpperCAmelCase) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Optional[Any] = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : int = 'lower newer' __A : Any = self.prepare_image_inputs() __A : Tuple = processor(text=_UpperCAmelCase , images=_UpperCAmelCase) self.assertListEqual(list(inputs.keys()) , ['input_ids', 'attention_mask', 'pixel_values']) # test if it raises when no input is passed with pytest.raises(_UpperCAmelCase): processor() def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = self.get_image_processor() __A : str = self.get_tokenizer() __A : Optional[Any] = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : str = processor.batch_decode(_UpperCAmelCase) __A : Optional[Any] = tokenizer.batch_decode(_UpperCAmelCase) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Optional[int] = self.get_image_processor() __A : int = self.get_tokenizer() __A : Any = CLIPProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : Any = 'lower newer' __A : Any = self.prepare_image_inputs() __A : Any = processor(text=_UpperCAmelCase , images=_UpperCAmelCase) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
190
1
def A(__a: int ): lowerCAmelCase_ = int(__a ) if n_element < 1: lowerCAmelCase_ = ValueError("a should be a positive number" ) raise my_error lowerCAmelCase_ = [1] lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = (0, 0, 0) lowerCAmelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowerCamelCase__ = input('''Enter the last number (nth term) of the Hamming Number Series: ''') print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''') lowerCamelCase__ = hamming(int(n)) print('''-----------------------------------------------------''') print(F'''The list with nth numbers is: {hamming_numbers}''') print('''-----------------------------------------------------''')
354
import datasets lowerCamelCase__ = '''\ @InProceedings{conneau2018xnli, author = "Conneau, Alexis and Rinott, Ruty and Lample, Guillaume and Williams, Adina and Bowman, Samuel R. and Schwenk, Holger and Stoyanov, Veselin", title = "XNLI: Evaluating Cross-lingual Sentence Representations", booktitle = "Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing", year = "2018", publisher = "Association for Computational Linguistics", location = "Brussels, Belgium", } ''' lowerCamelCase__ = '''\ XNLI is a subset of a few thousand examples from MNLI which has been translated into a 14 different languages (some low-ish resource). As with MNLI, the goal is to predict textual entailment (does sentence A imply/contradict/neither sentence B) and is a classification task (given two sentences, predict one of three labels). ''' lowerCamelCase__ = ''' Computes XNLI score which is just simple accuracy. Args: predictions: Predicted labels. references: Ground truth labels. Returns: \'accuracy\': accuracy Examples: >>> predictions = [0, 1] >>> references = [0, 1] >>> xnli_metric = datasets.load_metric("xnli") >>> results = xnli_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} ''' def A(__a: Dict , __a: Union[str, Any] ): return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __magic_name__ (datasets.Metric ): def __a ( self ) -> Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("int64" if self.config_name != "sts-b" else "float32" ), "references": datasets.Value("int64" if self.config_name != "sts-b" else "float32" ), } ) , codebase_urls=[] , reference_urls=[] , format="numpy" , ) def __a ( self , _a , _a ) -> List[str]: return {"accuracy": simple_accuracy(_a , _a )}
22
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase__ = {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""ViTFeatureExtractor"""] UpperCamelCase__ = ["""ViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """VIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTForImageClassification""", """ViTForMaskedImageModeling""", """ViTModel""", """ViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """TFViTForImageClassification""", """TFViTModel""", """TFViTPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """FlaxViTForImageClassification""", """FlaxViTModel""", """FlaxViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = 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 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , 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() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
1
from itertools import permutations def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> bool: if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False lowerCamelCase__ : Dict = [7, 11, 13, 17] for i, test in enumerate(_UpperCAmelCase ): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def SCREAMING_SNAKE_CASE ( _UpperCAmelCase = 10 ) -> int: return sum( int(''.join(map(_UpperCAmelCase , _UpperCAmelCase ) ) ) for num in permutations(range(_UpperCAmelCase ) ) if is_substring_divisible(_UpperCAmelCase ) ) if __name__ == "__main__": print(F"""{solution() = }""")
45
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase ( unittest.TestCase ): def __init__( self : Dict , UpperCAmelCase : List[str] , UpperCAmelCase : Any=7 , UpperCAmelCase : int=3 , UpperCAmelCase : Optional[Any]=18 , UpperCAmelCase : str=30 , UpperCAmelCase : List[str]=400 , UpperCAmelCase : int=True , UpperCAmelCase : List[Any]=None , UpperCAmelCase : str=True , UpperCAmelCase : Optional[int]=None , UpperCAmelCase : Union[str, Any]=True , UpperCAmelCase : List[str]=[0.5, 0.5, 0.5] , UpperCAmelCase : Union[str, Any]=[0.5, 0.5, 0.5] , ) -> Tuple: lowerCamelCase__ : Union[str, Any] = size if size is not None else {'shortest_edge': 18} lowerCamelCase__ : Union[str, Any] = crop_size if crop_size is not None else {'height': 18, 'width': 18} lowerCamelCase__ : Optional[Any] = parent lowerCamelCase__ : int = batch_size lowerCamelCase__ : str = num_channels lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : List[str] = min_resolution lowerCamelCase__ : Union[str, Any] = max_resolution lowerCamelCase__ : Optional[int] = do_resize lowerCamelCase__ : int = size lowerCamelCase__ : Optional[int] = do_center_crop lowerCamelCase__ : str = crop_size lowerCamelCase__ : Optional[Any] = do_normalize lowerCamelCase__ : Tuple = image_mean lowerCamelCase__ : Union[str, Any] = image_std def A_ ( self : Any ) -> Optional[int]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class lowerCAmelCase ( __UpperCamelCase, unittest.TestCase ): UpperCAmelCase__ = LevitImageProcessor if is_vision_available() else None def A_ ( self : Tuple ) -> Tuple: lowerCamelCase__ : str = LevitImageProcessingTester(self ) @property def A_ ( self : Tuple ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def A_ ( self : Optional[int] ) -> int: lowerCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase , 'image_mean' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'image_std' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'do_normalize' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'do_center_crop' ) ) self.assertTrue(hasattr(UpperCAmelCase , 'size' ) ) def A_ ( self : List[Any] ) -> Optional[int]: lowerCamelCase__ : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) lowerCamelCase__ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def A_ ( self : str ) -> str: pass def A_ ( self : Optional[int] ) -> List[Any]: # Initialize image_processing lowerCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase__ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , Image.Image ) # Test not batched input lowerCamelCase__ : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowerCamelCase__ : Optional[Any] = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def A_ ( self : List[str] ) -> List[Any]: # Initialize image_processing lowerCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , numpify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , np.ndarray ) # Test not batched input lowerCamelCase__ : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowerCamelCase__ : Any = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def A_ ( self : str ) -> int: # Initialize image_processing lowerCamelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , torchify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , torch.Tensor ) # Test not batched input lowerCamelCase__ : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowerCamelCase__ : Any = image_processing(UpperCAmelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
45
1
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class snake_case_ ( __A ,unittest.TestCase ): __A : int = RoCBertTokenizer __A : List[str] = None __A : Dict = False __A : Optional[int] = True __A : List[Any] = filter_non_english def __UpperCamelCase ( self : Dict ) -> Any: super().setUp() lowercase__ : Dict = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] lowercase__ : List[str] = {} lowercase__ : List[str] = {} for i, value in enumerate(lowercase_ ): lowercase__ : Union[str, Any] = i lowercase__ : Tuple = i lowercase__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) lowercase__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(lowercase_ , lowercase_ , ensure_ascii=lowercase_ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(lowercase_ , lowercase_ , ensure_ascii=lowercase_ ) def __UpperCamelCase ( self : Dict ) -> List[str]: lowercase__ : str = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) lowercase__ : Any = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(lowercase_ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(lowercase_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(lowercase_ ) , [5, 6, 2, 5, 7, 8] ) def __UpperCamelCase ( self : List[str] ) -> Optional[Any]: lowercase__ : List[str] = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __UpperCamelCase ( self : List[str] ) -> Dict: lowercase__ : Optional[int] = RoCBertBasicTokenizer(do_lower_case=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __UpperCamelCase ( self : List[str] ) -> Tuple: lowercase__ : int = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def __UpperCamelCase ( self : Dict ) -> List[str]: lowercase__ : Any = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: lowercase__ : Any = RoCBertBasicTokenizer(do_lower_case=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: lowercase__ : str = RoCBertBasicTokenizer(do_lower_case=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __UpperCamelCase ( self : Optional[int] ) -> List[str]: lowercase__ : Optional[int] = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: lowercase__ : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=lowercase_ , strip_accents=lowercase_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Tuple: lowercase__ : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=lowercase_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Dict: lowercase__ : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] lowercase__ : Union[str, Any] = {} for i, token in enumerate(lowercase_ ): lowercase__ : Optional[Any] = i lowercase__ : Dict = RoCBertWordpieceTokenizer(vocab=lowercase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def __UpperCamelCase ( self : str ) -> Tuple: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def __UpperCamelCase ( self : Dict ) -> int: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def __UpperCamelCase ( self : Dict ) -> Any: lowercase__ : int = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowercase_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: lowercase__ : Optional[Any] = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(lowercase_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __UpperCamelCase ( self : List[str] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase__ : Dict = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : List[Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' lowercase__ : str = tokenizer_r.encode_plus( lowercase_ , return_attention_mask=lowercase_ , return_token_type_ids=lowercase_ , return_offsets_mapping=lowercase_ , add_special_tokens=lowercase_ , ) lowercase__ : Any = tokenizer_r.do_lower_case if hasattr(lowercase_ , "do_lower_case" ) else False lowercase__ : Any = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: lowercase__ : Optional[Any] = ["的", "人", "有"] lowercase__ : Optional[Any] = "".join(lowercase_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase__ : Optional[Any] = True lowercase__ : str = self.tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Any = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Optional[int] = tokenizer_p.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : Optional[int] = tokenizer_r.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(lowercase_ ) lowercase__ : List[Any] = tokenizer_p.convert_ids_to_tokens(lowercase_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) lowercase__ : int = False lowercase__ : Any = self.rust_tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Union[str, Any] = self.tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) lowercase__ : Dict = tokenizer_r.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : List[str] = tokenizer_p.encode(lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : List[Any] = tokenizer_r.convert_ids_to_tokens(lowercase_ ) lowercase__ : str = tokenizer_p.convert_ids_to_tokens(lowercase_ ) # it is expected that only the first Chinese character is not preceded by "##". lowercase__ : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowercase_ ) ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) @slow def __UpperCamelCase ( self : Tuple ) -> int: lowercase__ : Optional[int] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) lowercase__ : Any = tokenizer.encode("你好" , add_special_tokens=lowercase_ ) lowercase__ : Dict = tokenizer.encode("你是谁" , add_special_tokens=lowercase_ ) lowercase__ : str = tokenizer.build_inputs_with_special_tokens(lowercase_ ) lowercase__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(lowercase_ , lowercase_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: lowercase__ : List[str] = self.get_tokenizers(do_lower_case=lowercase_ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): lowercase__ : int = "你好,你是谁" lowercase__ : int = tokenizer.tokenize(lowercase_ ) lowercase__ : str = tokenizer.convert_tokens_to_ids(lowercase_ ) lowercase__ : Tuple = tokenizer.convert_tokens_to_shape_ids(lowercase_ ) lowercase__ : int = tokenizer.convert_tokens_to_pronunciation_ids(lowercase_ ) lowercase__ : int = tokenizer.prepare_for_model( lowercase_ , lowercase_ , lowercase_ , add_special_tokens=lowercase_ ) lowercase__ : Any = tokenizer.encode_plus(lowercase_ , add_special_tokens=lowercase_ ) self.assertEqual(lowercase_ , lowercase_ )
87
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 = { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class snake_case_ ( __A ): __A : List[str] = "convbert" def __init__( self : Union[str, Any] , lowercase_ : str=3_05_22 , lowercase_ : Any=7_68 , lowercase_ : Tuple=12 , lowercase_ : List[str]=12 , lowercase_ : Optional[int]=30_72 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : str=0.1 , lowercase_ : List[str]=0.1 , lowercase_ : Optional[Any]=5_12 , lowercase_ : Dict=2 , lowercase_ : Union[str, Any]=0.02 , lowercase_ : Optional[Any]=1E-12 , lowercase_ : Optional[int]=1 , lowercase_ : List[Any]=0 , lowercase_ : Optional[int]=2 , lowercase_ : str=7_68 , lowercase_ : Dict=2 , lowercase_ : Optional[Any]=9 , lowercase_ : Union[str, Any]=1 , lowercase_ : Any=None , **lowercase_ : Optional[Any] , ) -> Dict: super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_ , ) lowercase__ : List[str] = vocab_size lowercase__ : Union[str, Any] = hidden_size lowercase__ : Any = num_hidden_layers lowercase__ : List[str] = num_attention_heads lowercase__ : Union[str, Any] = intermediate_size lowercase__ : Optional[Any] = hidden_act lowercase__ : int = hidden_dropout_prob lowercase__ : str = attention_probs_dropout_prob lowercase__ : Union[str, Any] = max_position_embeddings lowercase__ : Optional[int] = type_vocab_size lowercase__ : Tuple = initializer_range lowercase__ : List[str] = layer_norm_eps lowercase__ : List[Any] = embedding_size lowercase__ : Optional[Any] = head_ratio lowercase__ : Dict = conv_kernel_size lowercase__ : Tuple = num_groups lowercase__ : Optional[int] = classifier_dropout class snake_case_ ( __A ): @property def __UpperCamelCase ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowercase__ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: lowercase__ : str = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
87
1
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version _UpperCAmelCase : int = get_logger(__name__) class lowercase : __lowercase : List[str] = "dummy_data" __lowercase : int = "datasets" __lowercase : List[str] = False def __init__( self , A_ , A_ , A_ , A_ = None , A_ = False , A_ = True , A_ = None , ) -> List[str]: """simple docstring""" UpperCamelCase = 0 UpperCamelCase = dataset_name UpperCamelCase = cache_dir UpperCamelCase = use_local_dummy_data UpperCamelCase = config # download_callbacks take a single url as input UpperCamelCase = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root UpperCamelCase = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general UpperCamelCase = str(A_ ) # to be downloaded UpperCamelCase = None UpperCamelCase = None @property def __UpperCamelCase ( self ) -> Dict: """simple docstring""" if self._dummy_file is None: UpperCamelCase = self.download_dummy_data() return self._dummy_file @property def __UpperCamelCase ( self ) -> Any: """simple docstring""" if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('dummy' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('dummy' , self.version_name ) @property def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" return os.path.join(self.dummy_data_folder , 'dummy_data.zip' ) def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" UpperCamelCase = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) UpperCamelCase = cached_path( A_ , cache_dir=self.cache_dir , extract_compressed_file=A_ , force_extract=A_ ) return os.path.join(A_ , self.dummy_file_name ) @property def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __UpperCamelCase ( self ) -> str: """simple docstring""" if self._bucket_url is None: UpperCamelCase = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '/' ) ) return self._bucket_url @property def __UpperCamelCase ( self ) -> Dict: """simple docstring""" # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '/' ).split('/' )[:-1] ) def __UpperCamelCase ( self , A_ , *A_ ) -> Optional[Any]: """simple docstring""" if self.load_existing_dummy_data: # dummy data is downloaded and tested UpperCamelCase = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned UpperCamelCase = self.dummy_file_name # special case when data_url is a dict if isinstance(A_ , A_ ): return self.create_dummy_data_dict(A_ , A_ ) elif isinstance(A_ , (list, tuple) ): return self.create_dummy_data_list(A_ , A_ ) else: return self.create_dummy_data_single(A_ , A_ ) def __UpperCamelCase ( self , A_ , *A_ ) -> Tuple: """simple docstring""" return self.download_and_extract(A_ ) def __UpperCamelCase ( self , A_ , A_ ) -> List[Any]: """simple docstring""" return self.download_and_extract(A_ ) def __UpperCamelCase ( self , A_ , *A_ , **A_ ) -> Optional[int]: """simple docstring""" return path def __UpperCamelCase ( self ) -> str: """simple docstring""" return {} def __UpperCamelCase ( self , A_ , A_ ) -> Tuple: """simple docstring""" UpperCamelCase = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A_ , A_ ): for single_url in single_urls: download_callback(A_ ) else: UpperCamelCase = single_urls download_callback(A_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A_ , A_ ): UpperCamelCase = [os.path.join(A_ , urllib.parse.quote_plus(Path(A_ ).name ) ) for x in single_urls] else: UpperCamelCase = single_urls UpperCamelCase = os.path.join(A_ , urllib.parse.quote_plus(Path(A_ ).name ) ) UpperCamelCase = value # make sure that values are unique if all(isinstance(A_ , A_ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique UpperCamelCase = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __UpperCamelCase ( self , A_ , A_ ) -> Dict: """simple docstring""" UpperCamelCase = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one UpperCamelCase = all(bool(re.findall('[0-9]{3,}-of-[0-9]{3,}' , A_ ) ) for url in data_url ) UpperCamelCase = all( url.startswith('https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): UpperCamelCase = [data_url[0]] * len(A_ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus UpperCamelCase = os.path.join(A_ , urllib.parse.quote_plus(single_url.split('/' )[-1] ) ) dummy_data_list.append(A_ ) return dummy_data_list def __UpperCamelCase ( self , A_ , A_ ) -> Tuple: """simple docstring""" for download_callback in self.download_callbacks: download_callback(A_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus UpperCamelCase = os.path.join(A_ , urllib.parse.quote_plus(data_url.split('/' )[-1] ) ) if os.path.exists(A_ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" pass def __UpperCamelCase ( self ) -> str: """simple docstring""" pass def __UpperCamelCase ( self , A_ ) -> int: """simple docstring""" def _iter_archive_members(A_ ): # this preserves the order of the members inside the ZIP archive UpperCamelCase = Path(self.dummy_file ).parent UpperCamelCase = path.relative_to(A_ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: UpperCamelCase = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A_ ) UpperCamelCase = Path(A_ ) UpperCamelCase = _iter_archive_members(A_ ) if self.use_local_dummy_data else path.rglob('*' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('.', '__') ): yield file_path.relative_to(A_ ).as_posix(), file_path.open('rb' ) def __UpperCamelCase ( self , A_ ) -> int: """simple docstring""" if not isinstance(A_ , A_ ): UpperCamelCase = [paths] for path in paths: if os.path.isfile(A_ ): if os.path.basename(A_ ).startswith(('.', '__') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A_ ): if os.path.basename(A_ ).startswith(('.', '__') ): continue dirnames.sort() for filename in sorted(A_ ): if filename.startswith(('.', '__') ): continue yield os.path.join(A_ , A_ )
110
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def A ( ) -> int: '''simple docstring''' UpperCamelCase = 'https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png' UpperCamelCase = Image.open(requests.get(lowercase , stream=lowercase ).raw ).convert('RGB' ) return image def A ( lowercase ) -> Any: '''simple docstring''' UpperCamelCase = [] # fmt: off # vision encoder rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding') ) rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding') ) rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight') ) rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias') ) rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight') ) rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.weight''', f'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.bias''', f'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.weight''', f'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.bias''', f'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.attn.qkv.weight''', f'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.weight''', f'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.bias''', f'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.layernorm.weight') ) rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.layernorm.bias') ) # fmt: on return rename_keys def A ( lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' UpperCamelCase = dct.pop(lowercase ) UpperCamelCase = val def A ( lowercase , lowercase ) -> List[str]: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases UpperCamelCase = state_dict.pop(f'''visual_encoder.blocks.{i}.attn.q_bias''' ) UpperCamelCase = state_dict.pop(f'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict UpperCamelCase = torch.cat((q_bias, torch.zeros_like(lowercase , requires_grad=lowercase ), v_bias) ) UpperCamelCase = qkv_bias def A ( lowercase , lowercase ) -> int: '''simple docstring''' UpperCamelCase = 364 if 'coco' in model_name else 224 UpperCamelCase = BlipaVisionConfig(image_size=lowercase ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: UpperCamelCase = OPTConfig.from_pretrained('facebook/opt-2.7b' , eos_token_id=lowercase ).to_dict() elif "opt-6.7b" in model_name: UpperCamelCase = OPTConfig.from_pretrained('facebook/opt-6.7b' , eos_token_id=lowercase ).to_dict() elif "t5-xl" in model_name: UpperCamelCase = TaConfig.from_pretrained('google/flan-t5-xl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: UpperCamelCase = TaConfig.from_pretrained('google/flan-t5-xxl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() UpperCamelCase = BlipaConfig(vision_config=lowercase , text_config=lowercase ) return config, image_size @torch.no_grad() def A ( lowercase , lowercase=None , lowercase=False ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase = ( AutoTokenizer.from_pretrained('facebook/opt-2.7b' ) if 'opt' in model_name else AutoTokenizer.from_pretrained('google/flan-t5-xl' ) ) UpperCamelCase = tokenizer('\n' , add_special_tokens=lowercase ).input_ids[0] UpperCamelCase , UpperCamelCase = get_blipa_config(lowercase , eos_token_id=lowercase ) UpperCamelCase = BlipaForConditionalGeneration(lowercase ).eval() UpperCamelCase = { 'blip2-opt-2.7b': ('blip2_opt', 'pretrain_opt2.7b'), 'blip2-opt-6.7b': ('blip2_opt', 'pretrain_opt6.7b'), 'blip2-opt-2.7b-coco': ('blip2_opt', 'caption_coco_opt2.7b'), 'blip2-opt-6.7b-coco': ('blip2_opt', 'caption_coco_opt6.7b'), 'blip2-flan-t5-xl': ('blip2_t5', 'pretrain_flant5xl'), 'blip2-flan-t5-xl-coco': ('blip2_t5', 'caption_coco_flant5xl'), 'blip2-flan-t5-xxl': ('blip2_t5', 'pretrain_flant5xxl'), } UpperCamelCase , UpperCamelCase = model_name_to_original[model_name] # load original model print('Loading original model...' ) UpperCamelCase = 'cuda' if torch.cuda.is_available() else 'cpu' UpperCamelCase , UpperCamelCase , UpperCamelCase = load_model_and_preprocess( name=lowercase , model_type=lowercase , is_eval=lowercase , device=lowercase ) original_model.eval() print('Done!' ) # update state dict keys UpperCamelCase = original_model.state_dict() UpperCamelCase = create_rename_keys(lowercase ) for src, dest in rename_keys: rename_key(lowercase , lowercase , lowercase ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): UpperCamelCase = state_dict.pop(lowercase ) if key.startswith('Qformer.bert' ): UpperCamelCase = key.replace('Qformer.bert' , 'qformer' ) if "attention.self" in key: UpperCamelCase = key.replace('self' , 'attention' ) if "opt_proj" in key: UpperCamelCase = key.replace('opt_proj' , 'language_projection' ) if "t5_proj" in key: UpperCamelCase = key.replace('t5_proj' , 'language_projection' ) if key.startswith('opt' ): UpperCamelCase = key.replace('opt' , 'language' ) if key.startswith('t5' ): UpperCamelCase = key.replace('t5' , 'language' ) UpperCamelCase = val # read in qv biases read_in_q_v_bias(lowercase , lowercase ) UpperCamelCase , UpperCamelCase = hf_model.load_state_dict(lowercase , strict=lowercase ) assert len(lowercase ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] UpperCamelCase = load_demo_image() UpperCamelCase = vis_processors['eval'](lowercase ).unsqueeze(0 ).to(lowercase ) UpperCamelCase = tokenizer(['\n'] , return_tensors='pt' ).input_ids.to(lowercase ) # create processor UpperCamelCase = BlipImageProcessor( size={'height': image_size, 'width': image_size} , image_mean=lowercase , image_std=lowercase ) UpperCamelCase = BlipaProcessor(image_processor=lowercase , tokenizer=lowercase ) UpperCamelCase = processor(images=lowercase , return_tensors='pt' ).pixel_values.to(lowercase ) # make sure processor creates exact same pixel values assert torch.allclose(lowercase , lowercase ) original_model.to(lowercase ) hf_model.to(lowercase ) with torch.no_grad(): if "opt" in model_name: UpperCamelCase = original_model({'image': original_pixel_values, 'text_input': ['']} ).logits UpperCamelCase = hf_model(lowercase , lowercase ).logits else: UpperCamelCase = original_model( {'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']} ).logits UpperCamelCase = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) UpperCamelCase = hf_model(lowercase , lowercase , labels=lowercase ).logits assert original_logits.shape == logits.shape print('First values of original logits:' , original_logits[0, :3, :3] ) print('First values of HF logits:' , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": UpperCamelCase = torch.tensor( [[-4_1.5_8_5_0, -4.4_4_4_0, -8.9_9_2_2], [-4_7.4_3_2_2, -5.9_1_4_3, -1.7_3_4_0]] , device=lowercase ) assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) elif model_name == "blip2-flan-t5-xl-coco": UpperCamelCase = torch.tensor( [[-5_7.0_1_0_9, -9.8_9_6_7, -1_2.6_2_8_0], [-6_8.6_5_7_8, -1_2.7_1_9_1, -1_0.5_0_6_5]] , device=lowercase ) else: # cast to same type UpperCamelCase = logits.dtype assert torch.allclose(original_logits.to(lowercase ) , lowercase , atol=1e-2 ) print('Looks ok!' ) print('Generating a caption...' ) UpperCamelCase = '' UpperCamelCase = tokenizer(lowercase , return_tensors='pt' ).input_ids.to(lowercase ) UpperCamelCase = original_model.generate({'image': original_pixel_values} ) UpperCamelCase = hf_model.generate( lowercase , lowercase , do_sample=lowercase , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('Original generation:' , lowercase ) UpperCamelCase = input_ids.shape[1] UpperCamelCase = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=lowercase ) UpperCamelCase = [text.strip() for text in output_text] print('HF generation:' , lowercase ) if pytorch_dump_folder_path is not None: processor.save_pretrained(lowercase ) hf_model.save_pretrained(lowercase ) if push_to_hub: processor.push_to_hub(f'''nielsr/{model_name}''' ) hf_model.push_to_hub(f'''nielsr/{model_name}''' ) if __name__ == "__main__": _UpperCAmelCase : Optional[int] = argparse.ArgumentParser() _UpperCAmelCase : str = [ "blip2-opt-2.7b", "blip2-opt-6.7b", "blip2-opt-2.7b-coco", "blip2-opt-6.7b-coco", "blip2-flan-t5-xl", "blip2-flan-t5-xl-coco", "blip2-flan-t5-xxl", ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) _UpperCAmelCase : List[str] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
110
1
"""simple docstring""" import numpy as np import datasets snake_case__ : Dict = ''' 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/] ''' snake_case__ : Union[str, Any] = '''\ @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} } ''' snake_case__ : Any = ''' 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 snake_case_( datasets.Metric ): def lowerCamelCase__ ( self : List[str] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''' , id='''sequence''' ) , id='''X''' ), } ) , ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int ): # convert to numpy arrays lowerCAmelCase : List[str] = np.array(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = np.array(UpperCamelCase_ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('''Expected `X` to be a 2D vector''' ) if len(reference_distribution.shape ) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''' ) if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' ) # Get mahalanobis distance for each prediction lowerCAmelCase : List[Any] = X - np.mean(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = np.cov(reference_distribution.T ) try: lowerCAmelCase : Dict = np.linalg.inv(UpperCamelCase_ ) except np.linalg.LinAlgError: lowerCAmelCase : List[str] = np.linalg.pinv(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = np.dot(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = np.dot(UpperCamelCase_ , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
60
"""simple docstring""" def _snake_case ( _snake_case : int ): if not isinstance(_snake_case , _snake_case ): raise TypeError('''only integers accepted as input''' ) else: lowerCAmelCase : List[str] = str(abs(_snake_case ) ) lowerCAmelCase : Optional[Any] = [list(_snake_case ) for char in range(len(_snake_case ) )] for index in range(len(_snake_case ) ): num_transpositions[index].pop(_snake_case ) return max( int(''''''.join(list(_snake_case ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('''doctest''').testmod()
60
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Dict = "philschmid/bart-large-cnn-samsum" snake_case__ : Tuple = ( "This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, " "and returns a summary of the text." ) snake_case__ : Any = "summarizer" snake_case__ : Optional[int] = AutoTokenizer snake_case__ : str = AutoModelForSeqaSeqLM snake_case__ : int = ["text"] snake_case__ : Tuple = ["text"] def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: return self.pre_processor(UpperCAmelCase__ , return_tensors="pt" , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Dict ) -> Union[str, Any]: return self.model.generate(**UpperCAmelCase__ )[0] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any] ) -> int: return self.pre_processor.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ )
195
"""simple docstring""" from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Tuple = logging.get_logger(__name__) a__ : List[Any] = { '''snap-research/efficientformer-l1-300''': ( '''https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "efficientformer" def __init__( self : Any , UpperCAmelCase__ : List[int] = [3, 2, 6, 4] , UpperCAmelCase__ : List[int] = [4_8, 9_6, 2_2_4, 4_4_8] , UpperCAmelCase__ : List[bool] = [True, True, True, True] , UpperCAmelCase__ : int = 4_4_8 , UpperCAmelCase__ : int = 3_2 , UpperCAmelCase__ : int = 4 , UpperCAmelCase__ : int = 7 , UpperCAmelCase__ : int = 5 , UpperCAmelCase__ : int = 8 , UpperCAmelCase__ : int = 4 , UpperCAmelCase__ : float = 0.0 , UpperCAmelCase__ : int = 1_6 , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : float = 0.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : float = 1E-5 , UpperCAmelCase__ : str = "gelu" , UpperCAmelCase__ : float = 0.02 , UpperCAmelCase__ : float = 1E-12 , UpperCAmelCase__ : int = 2_2_4 , UpperCAmelCase__ : float = 1E-05 , **UpperCAmelCase__ : Tuple , ) -> None: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = hidden_sizes __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = mlp_expansion_ratio __SCREAMING_SNAKE_CASE = downsamples __SCREAMING_SNAKE_CASE = dim __SCREAMING_SNAKE_CASE = key_dim __SCREAMING_SNAKE_CASE = attention_ratio __SCREAMING_SNAKE_CASE = resolution __SCREAMING_SNAKE_CASE = pool_size __SCREAMING_SNAKE_CASE = downsample_patch_size __SCREAMING_SNAKE_CASE = downsample_stride __SCREAMING_SNAKE_CASE = downsample_pad __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = num_metaad_blocks __SCREAMING_SNAKE_CASE = distillation __SCREAMING_SNAKE_CASE = use_layer_scale __SCREAMING_SNAKE_CASE = layer_scale_init_value __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = batch_norm_eps
195
1
'''simple docstring''' import itertools import math def a_ ( __snake_case : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a_ ( ) -> List[str]: """simple docstring""" lowerCamelCase_ =2 while True: if is_prime(__snake_case ): yield num num += 1 def a_ ( __snake_case : int = 1_0001 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , __snake_case ) ) if __name__ == "__main__": print(F"""{solution() = }""")
75
'''simple docstring''' from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Any = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class __UpperCamelCase ( lowerCamelCase__ ): lowercase : List[str] ='efficientformer' def __init__( self, lowerCAmelCase = [3, 2, 6, 4], lowerCAmelCase = [48, 96, 224, 448], lowerCAmelCase = [True, True, True, True], lowerCAmelCase = 448, lowerCAmelCase = 32, lowerCAmelCase = 4, lowerCAmelCase = 7, lowerCAmelCase = 5, lowerCAmelCase = 8, lowerCAmelCase = 4, lowerCAmelCase = 0.0, lowerCAmelCase = 16, lowerCAmelCase = 3, lowerCAmelCase = 3, lowerCAmelCase = 3, lowerCAmelCase = 2, lowerCAmelCase = 1, lowerCAmelCase = 0.0, lowerCAmelCase = 1, lowerCAmelCase = True, lowerCAmelCase = True, lowerCAmelCase = 1e-5, lowerCAmelCase = "gelu", lowerCAmelCase = 0.0_2, lowerCAmelCase = 1e-12, lowerCAmelCase = 224, lowerCAmelCase = 1e-05, **lowerCAmelCase, ): """simple docstring""" super().__init__(**lowerCAmelCase ) lowerCamelCase_ =hidden_act lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =hidden_sizes lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =depths lowerCamelCase_ =mlp_expansion_ratio lowerCamelCase_ =downsamples lowerCamelCase_ =dim lowerCamelCase_ =key_dim lowerCamelCase_ =attention_ratio lowerCamelCase_ =resolution lowerCamelCase_ =pool_size lowerCamelCase_ =downsample_patch_size lowerCamelCase_ =downsample_stride lowerCamelCase_ =downsample_pad lowerCamelCase_ =drop_path_rate lowerCamelCase_ =num_metaad_blocks lowerCamelCase_ =distillation lowerCamelCase_ =use_layer_scale lowerCamelCase_ =layer_scale_init_value lowerCamelCase_ =image_size lowerCamelCase_ =batch_norm_eps
75
1
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCAmelCase : Any = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] UpperCAmelCase : Optional[Any] = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] UpperCAmelCase : Optional[int] = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) UpperCAmelCase : List[str] = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) UpperCAmelCase : List[Any] = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def a__ ( a__ , a__ ): """simple docstring""" for tf_name, hf_name in patterns: __SCREAMING_SNAKE_CASE = k.replace(a__ , a__ ) return k def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = BigBirdPegasusConfig(**a__ ) __SCREAMING_SNAKE_CASE = BigBirdPegasusForConditionalGeneration(a__ ) __SCREAMING_SNAKE_CASE = torch_model.state_dict() __SCREAMING_SNAKE_CASE = {} # separating decoder weights __SCREAMING_SNAKE_CASE = {k: tf_weights[k] for k in tf_weights if k.startswith("""pegasus/decoder""" )} __SCREAMING_SNAKE_CASE = {k: tf_weights[k] for k in tf_weights if not k.startswith("""pegasus/decoder""" )} for k, v in tqdm(decoder_weights.items() , """tf -> hf conversion""" ): __SCREAMING_SNAKE_CASE = [k.endswith(a__ ) for ending in KEYS_TO_IGNORE] if any(a__ ): continue __SCREAMING_SNAKE_CASE = DECODER_PATTERNS __SCREAMING_SNAKE_CASE = rename_state_dict_key(a__ , a__ ) if new_k not in state_dict: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["""dense""", """query""", """key""", """value"""] ): __SCREAMING_SNAKE_CASE = v.T __SCREAMING_SNAKE_CASE = torch.from_numpy(a__ ) assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' for k, v in tqdm(remaining_weights.items() , """tf -> hf conversion""" ): __SCREAMING_SNAKE_CASE = [k.endswith(a__ ) for ending in KEYS_TO_IGNORE] if any(a__ ): continue __SCREAMING_SNAKE_CASE = REMAINING_PATTERNS __SCREAMING_SNAKE_CASE = rename_state_dict_key(a__ , a__ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if any(True if i in k else False for i in ["""dense""", """query""", """key""", """value"""] ): __SCREAMING_SNAKE_CASE = v.T __SCREAMING_SNAKE_CASE = torch.from_numpy(a__ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}' __SCREAMING_SNAKE_CASE = mapping["""model.embed_positions.weight"""] __SCREAMING_SNAKE_CASE = mapping.pop("""model.embed_positions.weight""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torch_model.load_state_dict(a__ , strict=a__ ) __SCREAMING_SNAKE_CASE = [ k for k in missing if k not in [ """final_logits_bias""", """model.encoder.embed_tokens.weight""", """model.decoder.embed_tokens.weight""", """lm_head.weight""", ] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = tf.train.list_variables(a__ ) __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = ["""global_step"""] for name, shape in tqdm(a__ , desc="""converting tf checkpoint to dict""" ): __SCREAMING_SNAKE_CASE = any(pat in name for pat in ignore_name ) if skip_key: continue __SCREAMING_SNAKE_CASE = tf.train.load_variable(a__ , a__ ) __SCREAMING_SNAKE_CASE = array return tf_weights def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = get_tf_weights_as_numpy(a__ ) __SCREAMING_SNAKE_CASE = convert_bigbird_pegasus(a__ , a__ ) torch_model.save_pretrained(a__ ) if __name__ == "__main__": UpperCAmelCase : Any = argparse.ArgumentParser() parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.') UpperCAmelCase : int = parser.parse_args() UpperCAmelCase : Dict = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
352
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [[1, 2, 4], [1, 2, 3, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) self.assertTrue(isinstance(dc.token_ids , __SCREAMING_SNAKE_CASE ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) # fails here def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(3 ) __SCREAMING_SNAKE_CASE = stepped is True and completed is True and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
331
0
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) lowercase__ =logging.getLogger(__name__) class UpperCamelCase__ ( snake_case__ ): def lowerCAmelCase (self : Optional[int] , snake_case_ : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : str=None , snake_case_ : Dict=None ): __a : Optional[int] = self.layer[current_layer](snake_case_ , snake_case_ , head_mask[current_layer] ) __a : Any = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." ,snake_case__ ,) class UpperCamelCase__ ( snake_case__ ): def __init__(self : Union[str, Any] , snake_case_ : Optional[Any] ): super().__init__(snake_case_ ) __a : Any = BertEncoderWithPabee(snake_case_ ) self.init_weights() __a : Tuple = 0 __a : List[Any] = 0 __a : str = 0 __a : Union[str, Any] = 0 def lowerCAmelCase (self : Tuple , snake_case_ : Any ): __a : int = threshold def lowerCAmelCase (self : Union[str, Any] , snake_case_ : Dict ): __a : Any = patience def lowerCAmelCase (self : Union[str, Any] ): __a : Tuple = 0 __a : Union[str, Any] = 0 def lowerCAmelCase (self : int ): __a : List[str] = self.inference_layers_num / self.inference_instances_num __a : Tuple = ( f"*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =" f" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***" ) print(snake_case_ ) @add_start_docstrings_to_model_forward(snake_case_ ) def lowerCAmelCase (self : Optional[int] , snake_case_ : Optional[Any]=None , snake_case_ : List[str]=None , snake_case_ : Union[str, Any]=None , snake_case_ : List[Any]=None , snake_case_ : Any=None , snake_case_ : Tuple=None , snake_case_ : Dict=None , snake_case_ : Tuple=None , snake_case_ : List[str]=None , snake_case_ : List[str]=None , snake_case_ : List[str]=False , ): if input_ids is not None and inputs_embeds is not None: raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''' ) elif input_ids is not None: __a : List[str] = input_ids.size() elif inputs_embeds is not None: __a : List[Any] = inputs_embeds.size()[:-1] else: raise ValueError('''You have to specify either input_ids or inputs_embeds''' ) __a : Optional[Any] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __a : Tuple = torch.ones(snake_case_ , device=snake_case_ ) if token_type_ids is None: __a : Optional[int] = torch.zeros(snake_case_ , dtype=torch.long , device=snake_case_ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __a : str = self.get_extended_attention_mask(snake_case_ , snake_case_ , snake_case_ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: __a , __a , __a : str = encoder_hidden_states.size() __a : Optional[Any] = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: __a : List[Any] = torch.ones(snake_case_ , device=snake_case_ ) __a : List[Any] = self.invert_attention_mask(snake_case_ ) else: __a : int = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __a : Tuple = self.get_head_mask(snake_case_ , self.config.num_hidden_layers ) __a : Union[str, Any] = self.embeddings( input_ids=snake_case_ , position_ids=snake_case_ , token_type_ids=snake_case_ , inputs_embeds=snake_case_ ) __a : Dict = embedding_output if self.training: __a : List[str] = [] for i in range(self.config.num_hidden_layers ): __a : int = self.encoder.adaptive_forward( snake_case_ , current_layer=snake_case_ , attention_mask=snake_case_ , head_mask=snake_case_ ) __a : List[str] = self.pooler(snake_case_ ) __a : Union[str, Any] = output_layers[i](output_dropout(snake_case_ ) ) res.append(snake_case_ ) elif self.patience == 0: # Use all layers for inference __a : Union[str, Any] = self.encoder( snake_case_ , attention_mask=snake_case_ , head_mask=snake_case_ , encoder_hidden_states=snake_case_ , encoder_attention_mask=snake_case_ , ) __a : Optional[Any] = self.pooler(encoder_outputs[0] ) __a : str = [output_layers[self.config.num_hidden_layers - 1](snake_case_ )] else: __a : Dict = 0 __a : Tuple = None __a : Any = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 __a : Union[str, Any] = self.encoder.adaptive_forward( snake_case_ , current_layer=snake_case_ , attention_mask=snake_case_ , head_mask=snake_case_ ) __a : Union[str, Any] = self.pooler(snake_case_ ) __a : Tuple = output_layers[i](snake_case_ ) if regression: __a : int = logits.detach() if patient_result is not None: __a : List[str] = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: __a : List[Any] = 0 else: __a : List[str] = logits.detach().argmax(dim=1 ) if patient_result is not None: __a : Optional[int] = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(snake_case_ ) ): patient_counter += 1 else: __a : str = 0 __a : List[Any] = logits if patient_counter == self.patience: break __a : List[str] = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " ,snake_case__ ,) class UpperCamelCase__ ( snake_case__ ): def __init__(self : Union[str, Any] , snake_case_ : Optional[Any] ): super().__init__(snake_case_ ) __a : Any = config.num_labels __a : List[Any] = BertModelWithPabee(snake_case_ ) __a : Dict = nn.Dropout(config.hidden_dropout_prob ) __a : str = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(snake_case_ ) def lowerCAmelCase (self : Tuple , snake_case_ : Any=None , snake_case_ : Optional[Any]=None , snake_case_ : int=None , snake_case_ : Optional[int]=None , snake_case_ : str=None , snake_case_ : List[Any]=None , snake_case_ : Any=None , ): __a : Optional[Any] = self.bert( input_ids=snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , position_ids=snake_case_ , head_mask=snake_case_ , inputs_embeds=snake_case_ , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) __a : Any = (logits[-1],) if labels is not None: __a : Optional[Any] = None __a : Tuple = 0 for ix, logits_item in enumerate(snake_case_ ): if self.num_labels == 1: # We are doing regression __a : Dict = MSELoss() __a : Union[str, Any] = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: __a : Any = CrossEntropyLoss() __a : List[Any] = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: __a : Optional[Any] = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 __a : str = (total_loss / total_weights,) + outputs return outputs
216
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() _a = logging.get_logger(__name__) def __A ( __lowerCAmelCase , __lowerCAmelCase=False )-> Union[str, Any]: """simple docstring""" _UpperCAmelCase = [] 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'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _UpperCAmelCase = [(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 __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False )-> List[str]: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _UpperCAmelCase = '' else: _UpperCAmelCase = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCAmelCase = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) _UpperCAmelCase = state_dict.pop(F"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _UpperCAmelCase = in_proj_weight[ : config.hidden_size, : ] _UpperCAmelCase = in_proj_bias[: config.hidden_size] _UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCAmelCase = in_proj_weight[ -config.hidden_size :, : ] _UpperCAmelCase = in_proj_bias[-config.hidden_size :] def __A ( __lowerCAmelCase )-> Optional[Any]: """simple docstring""" _UpperCAmelCase = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> int: """simple docstring""" _UpperCAmelCase = dct.pop(__lowerCAmelCase ) _UpperCAmelCase = val def __A ( )-> str: """simple docstring""" _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) return im @torch.no_grad() def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=True )-> List[str]: """simple docstring""" _UpperCAmelCase = ViTConfig() # patch_size if model_name[-1] == "8": _UpperCAmelCase = 8 # set labels if required if not base_model: _UpperCAmelCase = 1_000 _UpperCAmelCase = 'huggingface/label-files' _UpperCAmelCase = 'imagenet-1k-id2label.json' _UpperCAmelCase = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase , repo_type='dataset' ) , 'r' ) ) _UpperCAmelCase = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: _UpperCAmelCase = 384 _UpperCAmelCase = 1_536 _UpperCAmelCase = 12 _UpperCAmelCase = 6 # load original model from torch hub _UpperCAmelCase = torch.hub.load('facebookresearch/dino:main' , __lowerCAmelCase ) original_model.eval() # load state_dict of original model, remove and rename some keys _UpperCAmelCase = original_model.state_dict() if base_model: remove_classification_head_(__lowerCAmelCase ) _UpperCAmelCase = create_rename_keys(__lowerCAmelCase , base_model=__lowerCAmelCase ) for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) read_in_q_k_v(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # load HuggingFace model if base_model: _UpperCAmelCase = ViTModel(__lowerCAmelCase , add_pooling_layer=__lowerCAmelCase ).eval() else: _UpperCAmelCase = ViTForImageClassification(__lowerCAmelCase ).eval() model.load_state_dict(__lowerCAmelCase ) # Check outputs on an image, prepared by ViTImageProcessor _UpperCAmelCase = ViTImageProcessor() _UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ) _UpperCAmelCase = encoding['pixel_values'] _UpperCAmelCase = model(__lowerCAmelCase ) if base_model: _UpperCAmelCase = original_model(__lowerCAmelCase ) assert torch.allclose(__lowerCAmelCase , outputs.last_hidden_state[:, 0, :] , atol=1E-1 ) else: _UpperCAmelCase = original_model(__lowerCAmelCase ) assert logits.shape == outputs.logits.shape assert torch.allclose(__lowerCAmelCase , outputs.logits , atol=1E-3 ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__lowerCAmelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": _a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''dino_vitb16''', type=str, help='''Name of the model trained with DINO you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--base_model''', action='''store_true''', help='''Whether to only convert the base model (no projection head weights).''', ) parser.set_defaults(base_model=True) _a = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
39
0
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) def __lowerCamelCase ( snake_case__ ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) _SCREAMING_SNAKE_CASE = re.match(r"""^mobilenet_v1_([^_]*)_([^_]*)$""" ,snake_case__ ) if matches: _SCREAMING_SNAKE_CASE = float(matches[1] ) _SCREAMING_SNAKE_CASE = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". _SCREAMING_SNAKE_CASE = 10_01 _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(snake_case__ ,snake_case__ ,repo_type="""dataset""" ) ,"""r""" ) ) _SCREAMING_SNAKE_CASE = {int(snake_case__ ) + 1: v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE = """background""" _SCREAMING_SNAKE_CASE = idalabel _SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" _SCREAMING_SNAKE_CASE = Image.open(requests.get(snake_case__ ,stream=snake_case__ ).raw ) return im @torch.no_grad() def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ,snake_case__=False ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE = get_mobilenet_va_config(snake_case__ ) # Load 🤗 model _SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification(snake_case__ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(snake_case__ ,snake_case__ ,snake_case__ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor _SCREAMING_SNAKE_CASE = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size} ,size={"""shortest_edge""": config.image_size + 32} ,) _SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() ,return_tensors="""pt""" ) _SCREAMING_SNAKE_CASE = model(**snake_case__ ) _SCREAMING_SNAKE_CASE = outputs.logits assert logits.shape == (1, 10_01) if model_name == "mobilenet_v1_1.0_224": _SCREAMING_SNAKE_CASE = torch.tensor([-4.1_739, -1.1_233, 3.1_205] ) elif model_name == "mobilenet_v1_0.75_192": _SCREAMING_SNAKE_CASE = torch.tensor([-3.9_440, -2.3_141, -0.3_333] ) else: _SCREAMING_SNAKE_CASE = None if expected_logits is not None: assert torch.allclose(logits[0, :3] ,snake_case__ ,atol=1e-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: print("""Pushing to the hub...""" ) _SCREAMING_SNAKE_CASE = """google/""" + model_name image_processor.push_to_hub(snake_case__ ) model.push_to_hub(snake_case__ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''mobilenet_v1_1.0_224''', type=str, help='''Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.''', ) parser.add_argument( '''--checkpoint_path''', required=True, type=str, help='''Path to the original TensorFlow checkpoint (.ckpt file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) UpperCamelCase = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
354
from __future__ import annotations import unittest from transformers import EsmConfig, 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 numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class __UpperCAmelCase : def __init__( self: Tuple , UpperCAmelCase_: Tuple , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = 13 _SCREAMING_SNAKE_CASE = 7 _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = 99 _SCREAMING_SNAKE_CASE = 32 _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = 4 _SCREAMING_SNAKE_CASE = 37 _SCREAMING_SNAKE_CASE = """gelu""" _SCREAMING_SNAKE_CASE = 0.1 _SCREAMING_SNAKE_CASE = 0.1 _SCREAMING_SNAKE_CASE = 512 _SCREAMING_SNAKE_CASE = 16 _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = 0.02 _SCREAMING_SNAKE_CASE = 3 _SCREAMING_SNAKE_CASE = 4 _SCREAMING_SNAKE_CASE = None def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE = None if self.use_input_mask: _SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None if self.use_labels: _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self: Tuple ): '''simple docstring''' ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCamelCase ( self: int , UpperCAmelCase_: Dict , UpperCAmelCase_: List[Any] , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: Dict , UpperCAmelCase_: Dict , UpperCAmelCase_: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TFEsmModel(config=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": input_mask} _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = [input_ids, input_mask] _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: Tuple , UpperCAmelCase_: Dict , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Tuple , UpperCAmelCase_: Any , UpperCAmelCase_: List[str] , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = TFEsmModel(config=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """attention_mask""": input_mask, """encoder_hidden_states""": encoder_hidden_states, """encoder_attention_mask""": encoder_attention_mask, } _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = [input_ids, input_mask] _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ ) # Also check the case where encoder outputs are not passed _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase ( self: Dict , UpperCAmelCase_: List[Any] , UpperCAmelCase_: List[Any] , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: List[str] , UpperCAmelCase_: str , UpperCAmelCase_: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TFEsmForMaskedLM(config=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase ( self: List[Any] , UpperCAmelCase_: Tuple , UpperCAmelCase_: str , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: int , UpperCAmelCase_: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = TFEsmForTokenClassification(config=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": input_mask} _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase ( self: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) = config_and_inputs _SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __UpperCAmelCase (_UpperCAmelCase ,_UpperCAmelCase ,unittest.TestCase ): __snake_case : List[Any] = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __snake_case : Tuple = ( { "feature-extraction": TFEsmModel, "fill-mask": TFEsmForMaskedLM, "text-classification": TFEsmForSequenceClassification, "token-classification": TFEsmForTokenClassification, "zero-shot": TFEsmForSequenceClassification, } if is_tf_available() else {} ) __snake_case : List[str] = False __snake_case : Union[str, Any] = False def UpperCamelCase ( self: Optional[int] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TFEsmModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def UpperCamelCase ( self: List[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def UpperCamelCase ( self: Tuple ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase_ ) def UpperCamelCase ( self: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_ ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) @slow def UpperCamelCase ( self: Tuple ): '''simple docstring''' for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE = TFEsmModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @unittest.skip("""Protein models do not support embedding resizing.""" ) def UpperCamelCase ( self: Dict ): '''simple docstring''' pass @unittest.skip("""Protein models do not support embedding resizing.""" ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' pass def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase_ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer _SCREAMING_SNAKE_CASE = model.get_bias() assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) for k, v in name.items(): assert isinstance(UpperCAmelCase_ , tf.Variable ) else: _SCREAMING_SNAKE_CASE = model.get_output_embeddings() assert x is None _SCREAMING_SNAKE_CASE = model.get_bias() assert name is None @require_tf class __UpperCAmelCase (unittest.TestCase ): @slow def UpperCamelCase ( self: Any ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TFEsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) _SCREAMING_SNAKE_CASE = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ )[0] _SCREAMING_SNAKE_CASE = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , UpperCAmelCase_ ) # compare the actual values for a slice. _SCREAMING_SNAKE_CASE = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def UpperCamelCase ( self: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TFEsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) _SCREAMING_SNAKE_CASE = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) _SCREAMING_SNAKE_CASE = model(UpperCAmelCase_ )[0] # compare the actual values for a slice. _SCREAMING_SNAKE_CASE = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
125
0
'''simple docstring''' import qiskit def __UpperCamelCase ( lowercase__ : int, lowercase__ : int ): '''simple docstring''' __lowercase =qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowercase =qiskit.QuantumCircuit(lowercase__, lowercase__ ) # Map the quantum measurement to the classical bits circuit.measure([0], [0] ) # Execute the circuit on the simulator __lowercase =qiskit.execute(lowercase__, lowercase__, shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print(F'''Total count for various states are: {single_qubit_measure(1, 1)}''')
141
'''simple docstring''' import unittest from transformers import AutoTokenizer, FalconConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class lowerCAmelCase : def __init__( self : Optional[int] , __lowercase : Dict , __lowercase : Optional[Any]=3 , __lowercase : Union[str, Any]=7 , __lowercase : Any=True , __lowercase : List[Any]=True , __lowercase : Union[str, Any]=False , __lowercase : int=True , __lowercase : List[str]=99 , __lowercase : int=32 , __lowercase : Dict=5 , __lowercase : Union[str, Any]=4 , __lowercase : List[Any]=37 , __lowercase : str="gelu" , __lowercase : int=0.1 , __lowercase : Dict=0.1 , __lowercase : Any=512 , __lowercase : List[str]=16 , __lowercase : Tuple=2 , __lowercase : Tuple=0.0_2 , __lowercase : List[str]=3 , __lowercase : Union[str, Any]=4 , __lowercase : List[Any]=None , ): """simple docstring""" __lowercase =parent __lowercase =batch_size __lowercase =seq_length __lowercase =is_training __lowercase =use_input_mask __lowercase =use_token_type_ids __lowercase =use_labels __lowercase =vocab_size __lowercase =hidden_size __lowercase =num_hidden_layers __lowercase =num_attention_heads __lowercase =intermediate_size __lowercase =hidden_act __lowercase =hidden_dropout_prob __lowercase =attention_probs_dropout_prob __lowercase =max_position_embeddings __lowercase =type_vocab_size __lowercase =type_sequence_label_size __lowercase =initializer_range __lowercase =num_labels __lowercase =num_choices __lowercase =scope def snake_case ( self : List[Any] ): """simple docstring""" __lowercase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase =None if self.use_input_mask: __lowercase =random_attention_mask([self.batch_size, self.seq_length] ) __lowercase =None __lowercase =None __lowercase =None __lowercase =None if self.use_labels: __lowercase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowercase =ids_tensor([self.batch_size] , self.num_choices ) __lowercase =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case ( self : Tuple ): """simple docstring""" return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowercase , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=__lowercase , ) def snake_case ( self : str , __lowercase : Optional[Any] , __lowercase : int , __lowercase : Any , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : Union[str, Any] , __lowercase : Optional[Any] ): """simple docstring""" __lowercase =FalconModel(config=__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model(__lowercase , attention_mask=__lowercase ) __lowercase =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self : Optional[Any] , __lowercase : Any , __lowercase : Union[str, Any] , __lowercase : List[Any] , __lowercase : str , __lowercase : Tuple , __lowercase : Optional[Any] , __lowercase : List[str] , __lowercase : Optional[Any] , __lowercase : List[str] , ): """simple docstring""" __lowercase =True __lowercase =FalconModel(__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , ) __lowercase =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , ) __lowercase =model(__lowercase , attention_mask=__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self : Union[str, Any] , __lowercase : int , __lowercase : List[Any] , __lowercase : List[str] , __lowercase : str , __lowercase : List[Any] , __lowercase : Tuple , __lowercase : Union[str, Any] , __lowercase : List[str] , __lowercase : Optional[int] , ): """simple docstring""" __lowercase =FalconForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case ( self : str , __lowercase : Union[str, Any] , __lowercase : Union[str, Any] , __lowercase : Optional[Any] , __lowercase : Dict , __lowercase : Optional[int] , __lowercase : Tuple , __lowercase : List[Any] , __lowercase : Dict , __lowercase : Tuple , ): """simple docstring""" __lowercase =True __lowercase =True __lowercase =FalconForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() # first forward pass __lowercase =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , use_cache=__lowercase , ) __lowercase =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __lowercase =ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowercase =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __lowercase =torch.cat([input_ids, next_tokens] , dim=-1 ) __lowercase =torch.cat([input_mask, next_mask] , dim=-1 ) __lowercase =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , output_hidden_states=__lowercase , )['hidden_states'][0] __lowercase =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , past_key_values=__lowercase , output_hidden_states=__lowercase , )['hidden_states'][0] # select random slice __lowercase =ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowercase =output_from_no_past[:, -3:, random_slice_idx].detach() __lowercase =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowercase , __lowercase , atol=1E-3 ) ) def snake_case ( self : Optional[Any] ): """simple docstring""" __lowercase =self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) =config_and_inputs __lowercase ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase ( A , A , A , unittest.TestCase ): lowerCAmelCase_ = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase_ = (FalconForCausalLM,) if is_torch_available() else () lowerCAmelCase_ = ( { "feature-extraction": FalconModel, "text-classification": FalconForSequenceClassification, "text-generation": FalconForCausalLM, "question-answering": FalconForQuestionAnswering, "token-classification": FalconForTokenClassification, "zero-shot": FalconForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = False def snake_case ( self : int ): """simple docstring""" __lowercase =FalconModelTester(self ) __lowercase =ConfigTester(self , config_class=__lowercase , hidden_size=37 ) def snake_case ( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self : Optional[Any] ): """simple docstring""" __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def snake_case ( self : Union[str, Any] ): """simple docstring""" __lowercase , *__lowercase =self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: __lowercase =alibi self.model_tester.create_and_check_model(__lowercase , *__lowercase ) def snake_case ( self : str ): """simple docstring""" __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() __lowercase =3 __lowercase =input_dict['input_ids'] __lowercase =input_ids.ne(1 ).to(__lowercase ) __lowercase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __lowercase =FalconForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def snake_case ( self : Optional[Any] ): """simple docstring""" __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() __lowercase =3 __lowercase ='single_label_classification' __lowercase =input_dict['input_ids'] __lowercase =input_ids.ne(1 ).to(__lowercase ) __lowercase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __lowercase =FalconForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def snake_case ( self : int ): """simple docstring""" __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() __lowercase =input_dict['input_ids'] __lowercase =FalconForCausalLM(__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model(__lowercase , use_cache=__lowercase ) __lowercase =input_ids.shape[0] __lowercase =model._convert_to_rw_cache(result.past_key_values ) __lowercase =model._convert_cache_to_standard_format(__lowercase , __lowercase ) for layer in range(len(__lowercase ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def snake_case ( self : Union[str, Any] ): """simple docstring""" __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() __lowercase =3 __lowercase ='multi_label_classification' __lowercase =input_dict['input_ids'] __lowercase =input_ids.ne(1 ).to(__lowercase ) __lowercase =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __lowercase =FalconForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() __lowercase =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def snake_case ( self : Tuple ): """simple docstring""" for model_class in self.all_generative_model_classes: __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(__lowercase , 'use_cache' ): return __lowercase =model_class(__lowercase ).to(__lowercase ) if "use_cache" not in inputs: __lowercase =True __lowercase =model(**__lowercase ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return __lowercase =( getattr(__lowercase , 'decoder_layers' , __lowercase ) or getattr(__lowercase , 'num_decoder_layers' , __lowercase ) or config.num_hidden_layers ) __lowercase =getattr(__lowercase , 'num_kv_heads' , config.num_attention_heads ) __lowercase =getattr(__lowercase , 'd_model' , config.hidden_size ) __lowercase =embed_dim // num_attention_heads __lowercase =outputs['past_key_values'] self.assertEqual(len(__lowercase ) , __lowercase ) __lowercase , __lowercase =inputs['input_ids'].shape for i in range(__lowercase ): if config.new_decoder_architecture: __lowercase =config.num_attention_heads elif config.multi_query: __lowercase =1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class lowerCAmelCase ( unittest.TestCase ): @slow def snake_case ( self : List[str] ): """simple docstring""" __lowercase =AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b' ) __lowercase =FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b' ) model.eval() model.to(__lowercase ) __lowercase =tokenizer('My favorite food is' , return_tensors='pt' ).to(__lowercase ) __lowercase =( 'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.' ) __lowercase =model.generate(**__lowercase , do_sample=__lowercase , max_new_tokens=19 ) __lowercase =tokenizer.batch_decode(__lowercase )[0] self.assertEqual(__lowercase , __lowercase ) @slow def snake_case ( self : Dict ): """simple docstring""" for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: __lowercase =AutoTokenizer.from_pretrained(__lowercase ) __lowercase =FalconForCausalLM.from_pretrained(__lowercase ) model.eval() model.to(__lowercase ) __lowercase =tokenizer('My favorite food is' , return_tensors='pt' ).to(__lowercase ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**__lowercase , do_sample=__lowercase , max_new_tokens=4 ) model.generate(**__lowercase , do_sample=__lowercase , max_new_tokens=4 ) model.generate(**__lowercase , num_beams=2 , max_new_tokens=4 ) @slow def snake_case ( self : Tuple ): """simple docstring""" with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: __lowercase =AutoTokenizer.from_pretrained(__lowercase ) __lowercase =FalconForCausalLM.from_pretrained(__lowercase ) model.eval() model.to(device=__lowercase ) __lowercase =tokenizer('My favorite food is' , return_tensors='pt' ).to(__lowercase ) # Test results are the same with and without cache __lowercase =model.generate(**__lowercase , do_sample=__lowercase , max_new_tokens=20 , use_cache=__lowercase ) __lowercase =model.generate(**__lowercase , do_sample=__lowercase , max_new_tokens=20 , use_cache=__lowercase ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
141
1
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = {"configuration_mmbt": ["MMBTConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ["MMBTForClassification", "MMBTModel", "ModalEmbeddings"] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
239
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE: def __init__( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__=13 ,SCREAMING_SNAKE_CASE__=7 ,SCREAMING_SNAKE_CASE__=True ,SCREAMING_SNAKE_CASE__=True ,SCREAMING_SNAKE_CASE__=True ,SCREAMING_SNAKE_CASE__=True ,SCREAMING_SNAKE_CASE__=99 ,SCREAMING_SNAKE_CASE__=32 ,SCREAMING_SNAKE_CASE__=5 ,SCREAMING_SNAKE_CASE__=4 ,SCREAMING_SNAKE_CASE__=37 ,SCREAMING_SNAKE_CASE__="gelu" ,SCREAMING_SNAKE_CASE__=0.1 ,SCREAMING_SNAKE_CASE__=0.1 ,SCREAMING_SNAKE_CASE__=5_12 ,SCREAMING_SNAKE_CASE__=16 ,SCREAMING_SNAKE_CASE__=2 ,SCREAMING_SNAKE_CASE__=0.0_2 ,SCREAMING_SNAKE_CASE__=3 ,SCREAMING_SNAKE_CASE__=4 ,SCREAMING_SNAKE_CASE__=None ,) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE :Any = parent __SCREAMING_SNAKE_CASE :Tuple = batch_size __SCREAMING_SNAKE_CASE :Tuple = seq_length __SCREAMING_SNAKE_CASE :Any = is_training __SCREAMING_SNAKE_CASE :Tuple = use_input_mask __SCREAMING_SNAKE_CASE :List[Any] = use_token_type_ids __SCREAMING_SNAKE_CASE :int = use_labels __SCREAMING_SNAKE_CASE :Dict = vocab_size __SCREAMING_SNAKE_CASE :int = hidden_size __SCREAMING_SNAKE_CASE :int = num_hidden_layers __SCREAMING_SNAKE_CASE :Union[str, Any] = num_attention_heads __SCREAMING_SNAKE_CASE :Any = intermediate_size __SCREAMING_SNAKE_CASE :Any = hidden_act __SCREAMING_SNAKE_CASE :str = hidden_dropout_prob __SCREAMING_SNAKE_CASE :List[str] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE :int = max_position_embeddings __SCREAMING_SNAKE_CASE :Any = type_vocab_size __SCREAMING_SNAKE_CASE :Optional[Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE :Optional[int] = initializer_range __SCREAMING_SNAKE_CASE :Union[str, Any] = num_labels __SCREAMING_SNAKE_CASE :Union[str, Any] = num_choices __SCREAMING_SNAKE_CASE :str = scope def _UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __SCREAMING_SNAKE_CASE :Union[str, Any] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE :List[str] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE :Union[str, Any] = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE :Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) __SCREAMING_SNAKE_CASE :Dict = None __SCREAMING_SNAKE_CASE :Dict = None __SCREAMING_SNAKE_CASE :Dict = None if self.use_labels: __SCREAMING_SNAKE_CASE :List[Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE :Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) __SCREAMING_SNAKE_CASE :Dict = ids_tensor([self.batch_size] ,self.num_choices ) __SCREAMING_SNAKE_CASE :Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=SCREAMING_SNAKE_CASE__ ,initializer_range=self.initializer_range ,) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE :List[Any] = NystromformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __SCREAMING_SNAKE_CASE :Any = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :List[str] = model(SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :int = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE :Dict = NystromformerForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __SCREAMING_SNAKE_CASE :Tuple = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE :List[str] = NystromformerForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __SCREAMING_SNAKE_CASE :Optional[Any] = model( SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,start_positions=SCREAMING_SNAKE_CASE__ ,end_positions=SCREAMING_SNAKE_CASE__ ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE :int = self.num_labels __SCREAMING_SNAKE_CASE :Any = NystromformerForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __SCREAMING_SNAKE_CASE :Dict = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = self.num_labels __SCREAMING_SNAKE_CASE :Tuple = NystromformerForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __SCREAMING_SNAKE_CASE :Any = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = self.num_choices __SCREAMING_SNAKE_CASE :Dict = NystromformerForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __SCREAMING_SNAKE_CASE :List[str] = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __SCREAMING_SNAKE_CASE :Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __SCREAMING_SNAKE_CASE :List[Any] = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __SCREAMING_SNAKE_CASE :Dict = model( SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__ ,token_type_ids=SCREAMING_SNAKE_CASE__ ,labels=SCREAMING_SNAKE_CASE__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _UpperCamelCase ( self ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE :List[Any] = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) , ) :Dict = config_and_inputs __SCREAMING_SNAKE_CASE :str = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE( A , A , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : int = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( { '''feature-extraction''': NystromformerModel, '''fill-mask''': NystromformerForMaskedLM, '''question-answering''': NystromformerForQuestionAnswering, '''text-classification''': NystromformerForSequenceClassification, '''token-classification''': NystromformerForTokenClassification, '''zero-shot''': NystromformerForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : Tuple = False def _UpperCamelCase ( self ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE :Any = NystromformerModelTester(self ) __SCREAMING_SNAKE_CASE :Optional[Any] = ConfigTester(self ,config_class=SCREAMING_SNAKE_CASE__ ,hidden_size=37 ) def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE :Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE :Any = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE :Tuple = NystromformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class _SCREAMING_SNAKE_CASE( unittest.TestCase ): @slow def _UpperCamelCase ( self ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE :int = NystromformerModel.from_pretrained('''uw-madison/nystromformer-512''' ) __SCREAMING_SNAKE_CASE :Dict = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE :str = model(SCREAMING_SNAKE_CASE__ )[0] __SCREAMING_SNAKE_CASE :Optional[int] = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :int = torch.tensor( [[[-0.4_5_3_2, -0.0_9_3_6, 0.5_1_3_7], [-0.2_6_7_6, 0.0_6_2_8, 0.6_1_8_6], [-0.3_6_2_9, -0.1_7_2_6, 0.4_7_1_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4 ) ) @slow def _UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = '''the [MASK] of Belgium is Brussels''' __SCREAMING_SNAKE_CASE :Optional[Any] = AutoTokenizer.from_pretrained('''uw-madison/nystromformer-512''' ) __SCREAMING_SNAKE_CASE :str = NystromformerForMaskedLM.from_pretrained('''uw-madison/nystromformer-512''' ) __SCREAMING_SNAKE_CASE :Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors='''pt''' ) with torch.no_grad(): __SCREAMING_SNAKE_CASE :Union[str, Any] = model(encoding.input_ids ).logits __SCREAMING_SNAKE_CASE :List[str] = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ,'''capital''' )
239
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _snake_case = { 'configuration_deberta': ['DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaConfig', 'DebertaOnnxConfig'], 'tokenization_deberta': ['DebertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['DebertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'DebertaForMaskedLM', 'DebertaForQuestionAnswering', 'DebertaForSequenceClassification', 'DebertaForTokenClassification', 'DebertaModel', 'DebertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ 'TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDebertaForMaskedLM', 'TFDebertaForQuestionAnswering', 'TFDebertaForSequenceClassification', 'TFDebertaForTokenClassification', 'TFDebertaModel', 'TFDebertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
294
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :Dict , lowercase_ :str = "▁" , lowercase_ :bool = True , lowercase_ :Union[str, AddedToken] = "<unk>" , lowercase_ :Union[str, AddedToken] = "</s>" , lowercase_ :Union[str, AddedToken] = "<pad>" , ) -> str: UpperCAmelCase = { 'pad': {'id': 0, 'token': pad_token}, 'eos': {'id': 1, 'token': eos_token}, 'unk': {'id': 2, 'token': unk_token}, } UpperCAmelCase = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): UpperCAmelCase = token_dict['token'] UpperCAmelCase = Tokenizer(Unigram() ) UpperCAmelCase = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(' {2,}' ) , ' ' ), normalizers.Lowercase(), ] ) UpperCAmelCase = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=lowercase_ , add_prefix_space=lowercase_ ), pre_tokenizers.Digits(individual_digits=lowercase_ ), pre_tokenizers.Punctuation(), ] ) UpperCAmelCase = decoders.Metaspace(replacement=lowercase_ , add_prefix_space=lowercase_ ) UpperCAmelCase = TemplateProcessing( single=f"""$A {self.special_tokens['eos']['token']}""" , special_tokens=[(self.special_tokens['eos']['token'], self.special_tokens['eos']['id'])] , ) UpperCAmelCase = { 'model': 'SentencePieceUnigram', 'replacement': replacement, 'add_prefix_space': add_prefix_space, } super().__init__(lowercase_ , lowercase_ ) def UpperCAmelCase__ ( self :Optional[int] , lowercase_ :Union[str, List[str]] , lowercase_ :int = 80_00 , lowercase_ :bool = True , ) -> Union[str, Any]: UpperCAmelCase = trainers.UnigramTrainer( vocab_size=lowercase_ , special_tokens=self.special_tokens_list , show_progress=lowercase_ , ) if isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = [files] self._tokenizer.train(lowercase_ , trainer=lowercase_ ) self.add_unk_id() def UpperCAmelCase__ ( self :str , lowercase_ :Union[Iterator[str], Iterator[Iterator[str]]] , lowercase_ :int = 80_00 , lowercase_ :bool = True , ) -> Tuple: UpperCAmelCase = trainers.UnigramTrainer( vocab_size=lowercase_ , special_tokens=self.special_tokens_list , show_progress=lowercase_ , ) self._tokenizer.train_from_iterator(lowercase_ , trainer=lowercase_ ) self.add_unk_id() def UpperCAmelCase__ ( self :Union[str, Any] ) -> int: UpperCAmelCase = json.loads(self._tokenizer.to_str() ) UpperCAmelCase = self.special_tokens['unk']['id'] UpperCAmelCase = Tokenizer.from_str(json.dumps(lowercase_ ) )
78
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) _a : int = logging.getLogger() def _lowerCAmelCase ( ) -> Optional[int]: __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""-f""" ) __lowerCAmelCase = parser.parse_args() return args.f def _lowerCAmelCase ( lowercase ) -> Optional[Any]: __lowerCAmelCase = {} __lowerCAmelCase = os.path.join(lowercase , """all_results.json""" ) if os.path.exists(lowercase ): with open(lowercase , """r""" ) as f: __lowerCAmelCase = json.load(lowercase ) else: raise ValueError(f'can\'t find {path}' ) return results def _lowerCAmelCase ( ) -> List[str]: __lowerCAmelCase = torch.cuda.is_available() and torch_device == """cuda""" return is_using_cuda and is_apex_available() _a : Union[str, Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _UpperCAmelCase ( lowerCAmelCase_ ): @classmethod def lowerCamelCase__ ( cls ): '''simple docstring''' __lowerCAmelCase = tempfile.mkdtemp() __lowerCAmelCase = os.path.join(cls.tmpdir,"""default_config.yml""" ) write_basic_config(save_location=cls.configPath ) __lowerCAmelCase = ["""accelerate""", """launch""", """--config_file""", cls.configPath] @classmethod def lowerCamelCase__ ( cls ): '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --seed=42\n --checkpointing_steps epoch\n --with_tracking\n '.split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_accuracy"""],0.75 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""glue_no_trainer""" ) ) ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --block_size 128\n --per_device_train_batch_size 5\n --per_device_eval_batch_size 5\n --num_train_epochs 2\n --output_dir {tmp_dir}\n --checkpointing_steps epoch\n --with_tracking\n '.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertLess(result["""perplexity"""],1_00 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""clm_no_trainer""" ) ) ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --num_train_epochs=1\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertLess(result["""perplexity"""],42 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""mlm_no_trainer""" ) ) ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = 7 if get_gpu_count() > 1 else 2 __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_accuracy"""],0.75 ) self.assertLess(result["""train_loss"""],0.5 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""ner_no_trainer""" ) ) ) @unittest.skip(reason="""Fix me @muellerzr""" ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --seed=42\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["""eval_f1"""],28 ) self.assertGreaterEqual(result["""eval_exact"""],28 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""qa_no_trainer""" ) ) ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/swag/sample.json\n --validation_file tests/fixtures/tests_samples/swag/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=20\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_accuracy"""],0.8 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""swag_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_rouge1"""],10 ) self.assertGreaterEqual(result["""eval_rouge2"""],2 ) self.assertGreaterEqual(result["""eval_rougeL"""],7 ) self.assertGreaterEqual(result["""eval_rougeLsum"""],7 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""summarization_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n --model_name_or_path sshleifer/student_marian_en_ro_6_1\n --source_lang en\n --target_lang ro\n --train_file tests/fixtures/tests_samples/wmt16/sample.json\n --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --num_beams=6\n --learning_rate=3e-3\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --source_lang en_XX\n --target_lang ro_RO\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_bleu"""],30 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""translation_no_trainer""" ) ) ) @slow def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = logging.StreamHandler(sys.stdout ) logger.addHandler(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n --dataset_name huggingface/semantic-segmentation-test-sample\n --output_dir {tmp_dir}\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n '.split() run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_overall_accuracy"""],0.10 ) @mock.patch.dict(os.environ,{"""WANDB_MODE""": """offline"""} ) def lowerCamelCase__ ( self ): '''simple docstring''' __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = f'\n {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n --model_name_or_path google/vit-base-patch16-224-in21k\n --dataset_name hf-internal-testing/cats_vs_dogs_sample\n --learning_rate 1e-4\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 1\n --max_train_steps 2\n --train_val_split 0.1\n --seed 42\n --output_dir {tmp_dir}\n --with_tracking\n --checkpointing_steps 1\n '.split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) __lowerCAmelCase = get_results(__SCREAMING_SNAKE_CASE ) # The base model scores a 25% self.assertGreaterEqual(result["""eval_accuracy"""],0.6 ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""step_1""" ) ) ) self.assertTrue(os.path.exists(os.path.join(__SCREAMING_SNAKE_CASE,"""image_classification_no_trainer""" ) ) )
360
'''simple docstring''' import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def _lowerCAmelCase ( lowercase , lowercase , lowercase ) -> List[str]: # Initialise PyTorch model __lowerCAmelCase = BertConfig.from_json_file(lowercase ) print(f'Building PyTorch model from configuration: {config}' ) __lowerCAmelCase = BertForPreTraining(lowercase ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase , lowercase , lowercase ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , lowercase ) if __name__ == "__main__": _a : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) _a : Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
46
0
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A__ = object() # For specifying empty leaf dict `{}` A__ = object() def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: """simple docstring""" snake_case__ : List[str] = tuple((re.compile(x + '''$''' ) for x in qs) ) for i in range(len(__lowerCAmelCase ) - len(__lowerCAmelCase ) + 1 ): snake_case__ : Optional[Any] = [x.match(__lowerCAmelCase ) for x, y in zip(__lowerCAmelCase , ks[i:] )] if matches and all(__lowerCAmelCase ): return True return False def _lowerCAmelCase ( __lowerCAmelCase ) -> List[str]: """simple docstring""" def replace(__lowerCAmelCase , __lowerCAmelCase ): for rule, replacement in rules: if _match(__lowerCAmelCase , __lowerCAmelCase ): return replacement return val return replace def _lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P('''mp''' , __lowerCAmelCase )), (("transformer", "wte", "embedding"), P('''mp''' , __lowerCAmelCase )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(__lowerCAmelCase , '''mp''' )), (("attention", "out_proj", "kernel"), P('''mp''' , __lowerCAmelCase )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(__lowerCAmelCase , '''mp''' )), (("mlp", "c_fc", "bias"), P('''mp''' )), (("mlp", "c_proj", "kernel"), P('''mp''' , __lowerCAmelCase )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( __lowerCAmelCase ) -> List[Any]: """simple docstring""" snake_case__ : Optional[int] = _get_partition_rules() snake_case__ : List[Any] = _replacement_rules(__lowerCAmelCase ) snake_case__ : Optional[Any] = {k: _unmatched for k in flatten_dict(__lowerCAmelCase )} snake_case__ : Dict = {k: replace(__lowerCAmelCase , __lowerCAmelCase ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(__lowerCAmelCase ) )
230
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging A__ = logging.get_logger(__name__) A__ = {'''vocab_file''': '''spiece.model'''} A__ = { '''vocab_file''': { '''TsinghuaAI/CPM-Generate''': '''https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model''', } } class a ( __lowerCamelCase ): def __init__( self :Union[str, Any] ,__lowercase :Optional[Any] ,__lowercase :int=False ,__lowercase :int=True ,__lowercase :Optional[int]=False ,__lowercase :List[str]="<s>" ,__lowercase :str="</s>" ,__lowercase :Dict="<unk>" ,__lowercase :Optional[int]="<sep>" ,__lowercase :Tuple="<pad>" ,__lowercase :Union[str, Any]="<cls>" ,__lowercase :Dict="<mask>" ,__lowercase :List[Any]=["<eop>", "<eod>"] ,__lowercase :Optional[Dict[str, Any]] = None ,**__lowercase :int ,): snake_case__ : Any = AddedToken(__lowercase ,lstrip=__lowercase ,rstrip=__lowercase ) if isinstance(__lowercase ,__lowercase ) else mask_token snake_case__ : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowercase ,remove_space=__lowercase ,keep_accents=__lowercase ,bos_token=__lowercase ,eos_token=__lowercase ,unk_token=__lowercase ,sep_token=__lowercase ,pad_token=__lowercase ,cls_token=__lowercase ,mask_token=__lowercase ,additional_special_tokens=__lowercase ,sp_model_kwargs=self.sp_model_kwargs ,**__lowercase ,) snake_case__ : Optional[Any] = 3 snake_case__ : List[str] = do_lower_case snake_case__ : Union[str, Any] = remove_space snake_case__ : Tuple = keep_accents snake_case__ : List[str] = vocab_file snake_case__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowercase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) snake_case__ : List[Any] = jieba snake_case__ : Union[str, Any] = str.maketrans(''' \n''' ,'''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def __lowerCamelCase ( self :Union[str, Any] ): return len(self.sp_model ) def __lowerCamelCase ( self :Any ): snake_case__ : Optional[Any] = {self.convert_ids_to_tokens(__lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self :List[str] ): snake_case__ : Optional[Any] = self.__dict__.copy() snake_case__ : Optional[int] = None return state def __setstate__( self :int ,__lowercase :str ): snake_case__ : Tuple = d # for backward compatibility if not hasattr(self ,'''sp_model_kwargs''' ): snake_case__ : List[Any] = {} snake_case__ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCamelCase ( self :Dict ,__lowercase :Optional[int] ): if self.remove_space: snake_case__ : int = ''' '''.join(inputs.strip().split() ) else: snake_case__ : Tuple = inputs snake_case__ : List[Any] = outputs.replace('''``''' ,'''"''' ).replace('''\'\'''' ,'''"''' ) if not self.keep_accents: snake_case__ : Any = unicodedata.normalize('''NFKD''' ,__lowercase ) snake_case__ : Dict = ''''''.join([c for c in outputs if not unicodedata.combining(__lowercase )] ) if self.do_lower_case: snake_case__ : str = outputs.lower() return outputs def __lowerCamelCase ( self :Optional[Any] ,__lowercase :str ): snake_case__ : Dict = self.preprocess_text(__lowercase ) snake_case__ : Any = self.sp_model.encode(__lowercase ,out_type=__lowercase ) snake_case__ : List[str] = [] for piece in pieces: if len(__lowercase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): snake_case__ : Union[str, Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowercase ,'''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case__ : Optional[Any] = cur_pieces[1:] else: snake_case__ : Optional[Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowercase ) else: new_pieces.append(__lowercase ) return new_pieces def __lowerCamelCase ( self :Union[str, Any] ,__lowercase :Dict ): return self.sp_model.PieceToId(__lowercase ) def __lowerCamelCase ( self :Tuple ,__lowercase :Optional[int] ): return self.sp_model.IdToPiece(__lowercase ) def __lowerCamelCase ( self :Tuple ,__lowercase :List[Any] ): snake_case__ : Union[str, Any] = ''''''.join(__lowercase ).replace(__lowercase ,''' ''' ).strip() return out_string def __lowerCamelCase ( self :List[Any] ,__lowercase :List[int] ,__lowercase :Optional[List[int]] = None ): snake_case__ : Optional[Any] = [self.sep_token_id] snake_case__ : str = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCamelCase ( self :str ,__lowercase :List[int] ,__lowercase :Optional[List[int]] = None ,__lowercase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase ,token_ids_a=__lowercase ,already_has_special_tokens=__lowercase ) if token_ids_a is not None: return ([0] * len(__lowercase )) + [1] + ([0] * len(__lowercase )) + [1, 1] return ([0] * len(__lowercase )) + [1, 1] def __lowerCamelCase ( self :List[str] ,__lowercase :List[int] ,__lowercase :Optional[List[int]] = None ): snake_case__ : List[Any] = [self.sep_token_id] snake_case__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCamelCase ( self :Optional[int] ,__lowercase :str ,__lowercase :Optional[str] = None ): if not os.path.isdir(__lowercase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case__ : Union[str, Any] = os.path.join( __lowercase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,__lowercase ) elif not os.path.isfile(self.vocab_file ): with open(__lowercase ,'''wb''' ) as fi: snake_case__ : str = self.sp_model.serialized_model_proto() fi.write(__lowercase ) return (out_vocab_file,) def __lowerCamelCase ( self :Union[str, Any] ,*__lowercase :Optional[int] ,**__lowercase :Dict ): snake_case__ : Dict = super()._decode(*__lowercase ,**__lowercase ) snake_case__ : List[Any] = text.replace(''' ''' ,'''''' ).replace('''\u2582''' ,''' ''' ).replace('''\u2583''' ,'''\n''' ) return text
230
1
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): def __init__( self : Any): """simple docstring""" self.test() def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = 0 lowercase_ = False while not completed: if counter == 1: self.reset() lowercase_ = self.advance() if not self.does_advance(lowerCAmelCase_): raise Exception( """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.""") lowercase_ , lowercase_ , lowercase_ = self.update(lowerCAmelCase_) counter += 1 if counter > 1_0_0_0_0: raise Exception("""update() does not fulfill the constraint.""") if self.remaining() != 0: raise Exception("""Custom Constraint is not defined correctly.""") @abstractmethod def _UpperCAmelCase ( self : int): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') @abstractmethod def _UpperCAmelCase ( self : Tuple , lowerCAmelCase_ : int): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') @abstractmethod def _UpperCAmelCase ( self : Tuple , lowerCAmelCase_ : int): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') @abstractmethod def _UpperCAmelCase ( self : str): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') @abstractmethod def _UpperCAmelCase ( self : str): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') @abstractmethod def _UpperCAmelCase ( self : Tuple , lowerCAmelCase_ : List[str]=False): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''') class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): def __init__( self : List[str] , lowerCAmelCase_ : List[int]): """simple docstring""" super(lowerCAmelCase_ , self).__init__() if not isinstance(lowerCAmelCase_ , lowerCAmelCase_) or len(lowerCAmelCase_) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''') if any((not isinstance(lowerCAmelCase_ , lowerCAmelCase_) or token_id < 0) for token_id in token_ids): raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''') lowercase_ = token_ids lowercase_ = len(self.token_ids) lowercase_ = -1 # the index of the currently fulfilled step lowercase_ = False def _UpperCAmelCase ( self : List[str]): """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def _UpperCAmelCase ( self : str , lowerCAmelCase_ : int): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowerCAmelCase_)}''') if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def _UpperCAmelCase ( self : int , lowerCAmelCase_ : int): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowerCAmelCase_)}''') lowercase_ = False lowercase_ = False lowercase_ = False if self.does_advance(lowerCAmelCase_): self.fulfilled_idx += 1 lowercase_ = True if self.fulfilled_idx == (self.seqlen - 1): lowercase_ = True lowercase_ = completed else: # failed to make progress. lowercase_ = True self.reset() return stepped, completed, reset def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = False lowercase_ = 0 def _UpperCAmelCase ( self : List[str]): """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def _UpperCAmelCase ( self : Optional[int] , lowerCAmelCase_ : Union[str, Any]=False): """simple docstring""" lowercase_ = PhrasalConstraint(self.token_ids) if stateful: lowercase_ = self.seqlen lowercase_ = self.fulfilled_idx lowercase_ = self.completed return new_constraint class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , lowerCAmelCase_ : List[List[int]] , lowerCAmelCase_ : Union[str, Any]=True): """simple docstring""" lowercase_ = max([len(lowerCAmelCase_) for one in nested_token_ids]) lowercase_ = {} for token_ids in nested_token_ids: lowercase_ = root for tidx, token_id in enumerate(lowerCAmelCase_): if token_id not in level: lowercase_ = {} lowercase_ = level[token_id] if no_subsets and self.has_subsets(lowerCAmelCase_ , lowerCAmelCase_): raise ValueError( """Each list in `nested_token_ids` can't be a complete subset of another list, but is""" F''' {nested_token_ids}.''') lowercase_ = root def _UpperCAmelCase ( self : int , lowerCAmelCase_ : Any): """simple docstring""" lowercase_ = self.trie for current_token in current_seq: lowercase_ = start[current_token] lowercase_ = list(start.keys()) return next_tokens def _UpperCAmelCase ( self : List[Any] , lowerCAmelCase_ : int): """simple docstring""" lowercase_ = self.next_tokens(lowerCAmelCase_) return len(lowerCAmelCase_) == 0 def _UpperCAmelCase ( self : Optional[int] , lowerCAmelCase_ : Any): """simple docstring""" lowercase_ = list(root.values()) if len(lowerCAmelCase_) == 0: return 1 else: return sum([self.count_leaves(lowerCAmelCase_) for nn in next_nodes]) def _UpperCAmelCase ( self : List[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : List[str]): """simple docstring""" lowercase_ = self.count_leaves(lowerCAmelCase_) return len(lowerCAmelCase_) != leaf_count class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): def __init__( self : str , lowerCAmelCase_ : List[List[int]]): """simple docstring""" super(lowerCAmelCase_ , self).__init__() if not isinstance(lowerCAmelCase_ , lowerCAmelCase_) or len(lowerCAmelCase_) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''') if any(not isinstance(lowerCAmelCase_ , lowerCAmelCase_) for token_ids in nested_token_ids): raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''') if any( any((not isinstance(lowerCAmelCase_ , lowerCAmelCase_) or token_id < 0) for token_id in token_ids) for token_ids in nested_token_ids): raise ValueError( F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''') lowercase_ = DisjunctiveTrie(lowerCAmelCase_) lowercase_ = nested_token_ids lowercase_ = self.trie.max_height lowercase_ = [] lowercase_ = False def _UpperCAmelCase ( self : int): """simple docstring""" lowercase_ = self.trie.next_tokens(self.current_seq) if len(lowerCAmelCase_) == 0: return None else: return token_list def _UpperCAmelCase ( self : Union[str, Any] , lowerCAmelCase_ : int): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCAmelCase_)}''') lowercase_ = self.trie.next_tokens(self.current_seq) return token_id in next_tokens def _UpperCAmelCase ( self : List[str] , lowerCAmelCase_ : int): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCAmelCase_)}''') lowercase_ = False lowercase_ = False lowercase_ = False if self.does_advance(lowerCAmelCase_): self.current_seq.append(lowerCAmelCase_) lowercase_ = True else: lowercase_ = True self.reset() lowercase_ = self.trie.reached_leaf(self.current_seq) lowercase_ = completed return stepped, completed, reset def _UpperCAmelCase ( self : Optional[int]): """simple docstring""" lowercase_ = False lowercase_ = [] def _UpperCAmelCase ( self : str): """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq) def _UpperCAmelCase ( self : List[Any] , lowerCAmelCase_ : str=False): """simple docstring""" lowercase_ = DisjunctiveConstraint(self.token_ids) if stateful: lowercase_ = self.seqlen lowercase_ = self.current_seq lowercase_ = self.completed return new_constraint class SCREAMING_SNAKE_CASE__ : def __init__( self : Optional[int] , lowerCAmelCase_ : List[Constraint]): """simple docstring""" lowercase_ = constraints # max # of steps required to fulfill a given constraint lowercase_ = max([c.seqlen for c in constraints]) lowercase_ = len(lowerCAmelCase_) lowercase_ = False self.init_state() def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" lowercase_ = [] lowercase_ = None lowercase_ = [constraint.copy(stateful=lowerCAmelCase_) for constraint in self.constraints] def _UpperCAmelCase ( self : Union[str, Any]): """simple docstring""" lowercase_ = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints) * self.max_seqlen) + add def _UpperCAmelCase ( self : Any): """simple docstring""" lowercase_ = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" lowercase_ = constraint.advance() if isinstance(lowerCAmelCase_ , lowerCAmelCase_): token_list.append(lowerCAmelCase_) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_): token_list.extend(lowerCAmelCase_) else: lowercase_ = self.inprogress_constraint.advance() if isinstance(lowerCAmelCase_ , lowerCAmelCase_): token_list.append(lowerCAmelCase_) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_): token_list.extend(lowerCAmelCase_) if len(lowerCAmelCase_) == 0: return None else: return token_list def _UpperCAmelCase ( self : Union[str, Any] , lowerCAmelCase_ : Optional[List[int]]): """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint lowercase_ , lowercase_ = self.add(lowerCAmelCase_) # the entire list of constraints are fulfilled if self.completed: break def _UpperCAmelCase ( self : Any , lowerCAmelCase_ : int): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''') lowercase_ , lowercase_ = False, False if self.completed: lowercase_ = True lowercase_ = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state lowercase_ , lowercase_ , lowercase_ = self.inprogress_constraint.update(lowerCAmelCase_) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=lowerCAmelCase_)) lowercase_ = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint) lowercase_ = None if len(self.pending_constraints) == 0: # we're done! lowercase_ = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints): if pending_constraint.does_advance(lowerCAmelCase_): lowercase_ , lowercase_ , lowercase_ = pending_constraint.update(lowerCAmelCase_) if not stepped: raise Exception( """`constraint.update(token_id)` is not yielding incremental progress, """ """even though `constraint.does_advance(token_id)` is true.""") if complete: self.complete_constraints.append(lowerCAmelCase_) lowercase_ = None if not complete and stepped: lowercase_ = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". lowercase_ = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. lowercase_ = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def _UpperCAmelCase ( self : Optional[int] , lowerCAmelCase_ : int=True): """simple docstring""" lowercase_ = ConstraintListState(self.constraints) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: lowercase_ = [ constraint.copy(stateful=lowerCAmelCase_) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: lowercase_ = self.inprogress_constraint.copy(stateful=lowerCAmelCase_) lowercase_ = [constraint.copy() for constraint in self.pending_constraints] return new_state
313
"""simple docstring""" import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def _UpperCAmelCase ( self : str): """simple docstring""" lowercase_ = Vector([1, 2, 3]) self.assertEqual(x.component(0) , 1) self.assertEqual(x.component(2) , 3) lowercase_ = Vector() def _UpperCAmelCase ( self : Tuple): """simple docstring""" lowercase_ = Vector([0, 0, 0, 0, 0, 1]) self.assertEqual(str(lowerCAmelCase_) , """(0,0,0,0,0,1)""") def _UpperCAmelCase ( self : int): """simple docstring""" lowercase_ = Vector([1, 2, 3, 4]) self.assertEqual(len(lowerCAmelCase_) , 4) def _UpperCAmelCase ( self : Any): """simple docstring""" lowercase_ = Vector([1, 2]) lowercase_ = Vector([1, 2, 3, 4, 5]) lowercase_ = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) lowercase_ = Vector([1, -1, 1, -1, 2, -3, 4, -5]) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3) self.assertEqual(z.euclidean_length() , 0) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3) def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = Vector([1, 2, 3]) lowercase_ = Vector([1, 1, 1]) self.assertEqual((x + y).component(0) , 2) self.assertEqual((x + y).component(1) , 3) self.assertEqual((x + y).component(2) , 4) def _UpperCAmelCase ( self : List[Any]): """simple docstring""" lowercase_ = Vector([1, 2, 3]) lowercase_ = Vector([1, 1, 1]) self.assertEqual((x - y).component(0) , 0) self.assertEqual((x - y).component(1) , 1) self.assertEqual((x - y).component(2) , 2) def _UpperCAmelCase ( self : Optional[int]): """simple docstring""" lowercase_ = Vector([1, 2, 3]) lowercase_ = Vector([2, -1, 4]) # for test of dot product lowercase_ = Vector([1, -2, -1]) self.assertEqual(str(x * 3.0) , """(3.0,6.0,9.0)""") self.assertEqual((a * b) , 0) def _UpperCAmelCase ( self : int): """simple docstring""" self.assertEqual(str(zero_vector(1_0)).count("""0""") , 1_0) def _UpperCAmelCase ( self : Dict): """simple docstring""" self.assertEqual(str(unit_basis_vector(3 , 1)) , """(0,1,0)""") def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" lowercase_ = Vector([1, 2, 3]) lowercase_ = Vector([1, 0, 1]) self.assertEqual(str(axpy(2 , lowerCAmelCase_ , lowerCAmelCase_)) , """(3,4,7)""") def _UpperCAmelCase ( self : List[Any]): """simple docstring""" lowercase_ = Vector([1, 0, 0, 0, 0, 0]) lowercase_ = x.copy() self.assertEqual(str(lowerCAmelCase_) , str(lowerCAmelCase_)) def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = Vector([1, 0, 0]) x.change_component(0 , 0) x.change_component(1 , 1) self.assertEqual(str(lowerCAmelCase_) , """(0,1,0)""") def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) self.assertEqual("""|1,2,3|\n|2,4,5|\n|6,7,8|\n""" , str(lowerCAmelCase_)) def _UpperCAmelCase ( self : str): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) lowercase_ = [[-3, -1_4, -1_0], [-5, -1_0, -5], [-2, -1, 0]] for x in range(a.height()): for y in range(a.width()): self.assertEqual(minors[x][y] , a.minor(lowerCAmelCase_ , lowerCAmelCase_)) def _UpperCAmelCase ( self : List[str]): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) lowercase_ = [[-3, 1_4, -1_0], [5, -1_0, 5], [-2, 1, 0]] for x in range(a.height()): for y in range(a.width()): self.assertEqual(cofactors[x][y] , a.cofactor(lowerCAmelCase_ , lowerCAmelCase_)) def _UpperCAmelCase ( self : List[str]): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) self.assertEqual(-5 , a.determinant()) def _UpperCAmelCase ( self : int): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3) lowercase_ = Vector([1, 2, 3]) self.assertEqual("""(14,32,50)""" , str(a * x)) self.assertEqual("""|2,4,6|\n|8,10,12|\n|14,16,18|\n""" , str(a * 2)) def _UpperCAmelCase ( self : List[str]): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) a.change_component(0 , 2 , 5) self.assertEqual("""|1,2,5|\n|2,4,5|\n|6,7,8|\n""" , str(lowerCAmelCase_)) def _UpperCAmelCase ( self : str): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) self.assertEqual(7 , a.component(2 , 1) , 0.01) def _UpperCAmelCase ( self : Dict): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) lowercase_ = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 1_0]] , 3 , 3) self.assertEqual("""|2,4,10|\n|4,8,10|\n|12,14,18|\n""" , str(a + b)) def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" lowercase_ = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3) lowercase_ = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 1_0]] , 3 , 3) self.assertEqual("""|0,0,-4|\n|0,0,0|\n|0,0,-2|\n""" , str(a - b)) def _UpperCAmelCase ( self : Optional[Any]): """simple docstring""" self.assertEqual( """|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n""" , str(square_zero_matrix(5)) , ) if __name__ == "__main__": unittest.main()
313
1
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class lowerCAmelCase_ ( snake_case__ ): __lowerCamelCase : str = 42 __lowerCamelCase : Optional[Any] = 42 class lowerCAmelCase_ ( snake_case__ ,snake_case__ ): __lowerCamelCase : Optional[int] = 1 @register_to_config def __init__( self , _lowerCAmelCase = 2000 , _lowerCAmelCase = 0.15 , _lowerCAmelCase = 0.01 , _lowerCAmelCase = 1348.0 , _lowerCAmelCase = 1E-5 , _lowerCAmelCase = 1 , ) -> str: _lowerCAmelCase = sigma_max # setable values _lowerCAmelCase = None self.set_sigmas(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None ) -> Union[str, Any]: return sample def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None ) -> str: _lowerCAmelCase = sampling_eps if sampling_eps is not None else self.config.sampling_eps _lowerCAmelCase = torch.linspace(1 , _lowerCAmelCase , _lowerCAmelCase , device=_lowerCAmelCase ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None ) -> Optional[int]: _lowerCAmelCase = sigma_min if sigma_min is not None else self.config.sigma_min _lowerCAmelCase = sigma_max if sigma_max is not None else self.config.sigma_max _lowerCAmelCase = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(_lowerCAmelCase , _lowerCAmelCase ) _lowerCAmelCase = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) _lowerCAmelCase = torch.exp(torch.linspace(math.log(_lowerCAmelCase ) , math.log(_lowerCAmelCase ) , _lowerCAmelCase ) ) _lowerCAmelCase = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = True , ) -> Any: if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler" ) _lowerCAmelCase = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) _lowerCAmelCase = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda _lowerCAmelCase = timesteps.to(self.discrete_sigmas.device ) _lowerCAmelCase = self.discrete_sigmas[timesteps].to(sample.device ) _lowerCAmelCase = self.get_adjacent_sigma(_lowerCAmelCase , _lowerCAmelCase ).to(sample.device ) _lowerCAmelCase = torch.zeros_like(_lowerCAmelCase ) _lowerCAmelCase = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods _lowerCAmelCase = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): _lowerCAmelCase = diffusion.unsqueeze(-1 ) _lowerCAmelCase = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of _lowerCAmelCase = randn_tensor( sample.shape , layout=sample.layout , generator=_lowerCAmelCase , device=sample.device , dtype=sample.dtype ) _lowerCAmelCase = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? _lowerCAmelCase = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=_lowerCAmelCase , prev_sample_mean=_lowerCAmelCase ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = True , ) -> Dict: if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler" ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction _lowerCAmelCase = randn_tensor(sample.shape , layout=sample.layout , generator=_lowerCAmelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr _lowerCAmelCase = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() _lowerCAmelCase = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() _lowerCAmelCase = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 _lowerCAmelCase = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term _lowerCAmelCase = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): _lowerCAmelCase = step_size.unsqueeze(-1 ) _lowerCAmelCase = sample + step_size * model_output _lowerCAmelCase = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowerCAmelCase ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ) -> Dict: _lowerCAmelCase = timesteps.to(original_samples.device ) _lowerCAmelCase = self.discrete_sigmas.to(original_samples.device )[timesteps] _lowerCAmelCase = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(_lowerCAmelCase ) * sigmas[:, None, None, None] ) _lowerCAmelCase = noise + original_samples return noisy_samples def __len__( self ) -> Union[str, Any]: return self.config.num_train_timesteps
158
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) _a = logging.getLogger() _a = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __lowerCamelCase ( snake_case__): """simple docstring""" def UpperCamelCase ( self , UpperCAmelCase ): """simple docstring""" os.makedirs(UpperCAmelCase , exist_ok=UpperCAmelCase ) _UpperCAmelCase = {'source': 'What is love ?', 'target': 'life'} _UpperCAmelCase = {'train': 12, 'val': 2, 'test': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: _UpperCAmelCase = '\n'.join([contents[field]] * n_lines[split] ) with open(os.path.join(UpperCAmelCase , F"""{split}.{field}""" ) , 'w' ) as f: f.write(UpperCAmelCase ) def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase = "pytorch" ): """simple docstring""" _UpperCAmelCase = self.get_auto_remove_tmp_dir() _UpperCAmelCase = os.path.join(UpperCAmelCase , 'output' ) _UpperCAmelCase = os.path.join(UpperCAmelCase , 'data' ) self._create_dummy_data(data_dir=UpperCAmelCase ) _UpperCAmelCase = F""" --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ """.split() if gpus > 0: testargs.append(F"""--gpus={gpus}""" ) if is_apex_available(): testargs.append('--fp16' ) else: testargs.append('--gpus=0' ) testargs.append('--distributed_backend=ddp_cpu' ) testargs.append('--num_processes=2' ) _UpperCAmelCase = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(UpperCAmelCase , env=self.get_env() ) _UpperCAmelCase = os.path.join(UpperCAmelCase , 'metrics.json' ) with open(UpperCAmelCase ) as f: _UpperCAmelCase = json.load(UpperCAmelCase ) return result @require_torch_gpu def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_multi_gpu def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_gpu @require_ray def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self._run_finetune(gpus=1 , distributed_retriever='ray' ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_multi_gpu @require_ray def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self._run_finetune(gpus=1 , distributed_retriever='ray' ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 )
39
0
import math def a__ ( __UpperCamelCase ): if not isinstance(__UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = F'''Input value of [number={number}] must be an integer''' raise TypeError(__UpperCamelCase ) if number < 1: SCREAMING_SNAKE_CASE_ = F'''Input value of [number={number}] must be > 0''' raise ValueError(__UpperCamelCase ) elif number == 1: return 3 elif number == 2: return 5 else: SCREAMING_SNAKE_CASE_ = int(math.log(number // 3 , 2 ) ) + 2 SCREAMING_SNAKE_CASE_ = [3, 5] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 3 for block in range(1 , __UpperCamelCase ): for _ in range(__UpperCamelCase ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): A : Dict = 0 try: A : Optional[Any] = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
305
from collections import deque class lowerCamelCase : """simple docstring""" def __init__( self : str , __magic_name__ : str , __magic_name__ : int , __magic_name__ : int ) -> None: SCREAMING_SNAKE_CASE_ = process_name # process name SCREAMING_SNAKE_CASE_ = arrival_time # arrival time of the process # completion time of finished process or last interrupted time SCREAMING_SNAKE_CASE_ = arrival_time SCREAMING_SNAKE_CASE_ = burst_time # remaining burst time SCREAMING_SNAKE_CASE_ = 0 # total time of the process wait in ready queue SCREAMING_SNAKE_CASE_ = 0 # time from arrival time to completion time class lowerCamelCase : """simple docstring""" def __init__( self : Tuple , __magic_name__ : int , __magic_name__ : list[int] , __magic_name__ : deque[Process] , __magic_name__ : int , ) -> None: # total number of mlfq's queues SCREAMING_SNAKE_CASE_ = number_of_queues # time slice of queues that round robin algorithm applied SCREAMING_SNAKE_CASE_ = time_slices # unfinished process is in this ready_queue SCREAMING_SNAKE_CASE_ = queue # current time SCREAMING_SNAKE_CASE_ = current_time # finished process is in this sequence queue SCREAMING_SNAKE_CASE_ = deque() def __A ( self : Dict ) -> list[str]: SCREAMING_SNAKE_CASE_ = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def __A ( self : List[str] , __magic_name__ : list[Process] ) -> list[int]: SCREAMING_SNAKE_CASE_ = [] for i in range(len(__magic_name__ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def __A ( self : List[str] , __magic_name__ : list[Process] ) -> list[int]: SCREAMING_SNAKE_CASE_ = [] for i in range(len(__magic_name__ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def __A ( self : Tuple , __magic_name__ : list[Process] ) -> list[int]: SCREAMING_SNAKE_CASE_ = [] for i in range(len(__magic_name__ ) ): completion_times.append(queue[i].stop_time ) return completion_times def __A ( self : str , __magic_name__ : deque[Process] ) -> list[int]: return [q.burst_time for q in queue] def __A ( self : Optional[Any] , __magic_name__ : Process ) -> int: process.waiting_time += self.current_time - process.stop_time return process.waiting_time def __A ( self : Optional[Any] , __magic_name__ : deque[Process] ) -> deque[Process]: SCREAMING_SNAKE_CASE_ = deque() # sequence deque of finished process while len(__magic_name__ ) != 0: SCREAMING_SNAKE_CASE_ = 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(__magic_name__ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 SCREAMING_SNAKE_CASE_ = 0 # set the process's turnaround time because it is finished SCREAMING_SNAKE_CASE_ = self.current_time - cp.arrival_time # set the completion time SCREAMING_SNAKE_CASE_ = self.current_time # add the process to queue that has finished queue finished.append(__magic_name__ ) self.finish_queue.extend(__magic_name__ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def __A ( self : Any , __magic_name__ : deque[Process] , __magic_name__ : int ) -> tuple[deque[Process], deque[Process]]: SCREAMING_SNAKE_CASE_ = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(__magic_name__ ) ): SCREAMING_SNAKE_CASE_ = 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(__magic_name__ ) # 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 SCREAMING_SNAKE_CASE_ = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(__magic_name__ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished SCREAMING_SNAKE_CASE_ = 0 # set the finish time SCREAMING_SNAKE_CASE_ = self.current_time # update the process' turnaround time because it is finished SCREAMING_SNAKE_CASE_ = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(__magic_name__ ) self.finish_queue.extend(__magic_name__ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def __A ( self : Any ) -> deque[Process]: # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 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 A : Dict = Process("P1", 0, 53) A : str = Process("P2", 0, 17) A : List[Any] = Process("P3", 0, 68) A : List[str] = Process("P4", 0, 24) A : Dict = 3 A : Any = [17, 25] A : Dict = 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])}) A : Union[str, Any] = Process("P1", 0, 53) A : Any = Process("P2", 0, 17) A : Dict = Process("P3", 0, 68) A : List[str] = Process("P4", 0, 24) A : Optional[int] = 3 A : int = [17, 25] A : Union[str, Any] = deque([Pa, Pa, Pa, Pa]) A : Tuple = MLFQ(number_of_queues, time_slices, queue, 0) A : Tuple = 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()}" )
305
1
import requests UpperCAmelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ): lowercase = 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>''')
195
'''simple docstring''' import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files" , [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ] , ) def UpperCAmelCase_ ( __lowercase : Any , __lowercase : int ) -> int: '''simple docstring''' _UpperCAmelCase = tmp_path_factory.mktemp("dset_infos_dir" ) if "full:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("---\ndataset_info:\n dataset_size: 42\n---" ) if "empty:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json" , "w" ) as f: f.write("{\"default\": {\"dataset_size\": 42}}" ) _UpperCAmelCase = DatasetInfosDict.from_directory(__lowercase ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( "dataset_info" , [ DatasetInfo(), DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=42 , ), ] , ) def UpperCAmelCase_ ( __lowercase : Tuple , __lowercase : DatasetInfo ) -> Any: '''simple docstring''' _UpperCAmelCase = str(__lowercase ) dataset_info.write_to_directory(__lowercase ) _UpperCAmelCase = DatasetInfo.from_directory(__lowercase ) assert dataset_info == reloaded assert os.path.exists(os.path.join(__lowercase , "dataset_info.json" ) ) def UpperCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase = DatasetInfo( description="foo" , citation="bar" , homepage="https://foo.bar" , license="CC0" , features=Features({"a": Value("int32" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train", "num_examples": 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) _UpperCAmelCase = dataset_info._to_yaml_dict() assert sorted(__lowercase ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) _UpperCAmelCase = yaml.safe_dump(__lowercase ) _UpperCAmelCase = yaml.safe_load(__lowercase ) assert dataset_info_yaml_dict == reloaded def UpperCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = DatasetInfo() _UpperCAmelCase = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict" , [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()} ), DatasetInfosDict({"my_config_name": DatasetInfo()} ), DatasetInfosDict( { "default": DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=42 , ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=42 ), "v2": DatasetInfo(dataset_size=1337 ), } ), ] , ) def UpperCAmelCase_ ( __lowercase : int , __lowercase : DatasetInfosDict ) -> Dict: '''simple docstring''' _UpperCAmelCase = str(__lowercase ) dataset_infos_dict.write_to_directory(__lowercase ) _UpperCAmelCase = DatasetInfosDict.from_directory(__lowercase ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): _UpperCAmelCase = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml _UpperCAmelCase = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(__lowercase , "README.md" ) )
22
0
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _snake_case ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" # Load configuration defined in the metadata file with open(_SCREAMING_SNAKE_CASE ) as metadata_file: lowerCAmelCase = json.load(_SCREAMING_SNAKE_CASE ) lowerCAmelCase = LukeConfig(use_entity_aware_attention=_SCREAMING_SNAKE_CASE , **metadata["""model_config"""] ) # Load in the weights from the checkpoint_path lowerCAmelCase = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )["""module"""] # Load the entity vocab file lowerCAmelCase = load_original_entity_vocab(_SCREAMING_SNAKE_CASE ) # add an entry for [MASK2] lowerCAmelCase = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 lowerCAmelCase = XLMRobertaTokenizer.from_pretrained(metadata["""model_config"""]["""bert_model_name"""] ) # Add special tokens to the token vocabulary for downstream tasks lowerCAmelCase = AddedToken("""<ent>""" , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) lowerCAmelCase = AddedToken("""<ent2>""" , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({"""additional_special_tokens""": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , """tokenizer_config.json""" ) , """r""" ) as f: lowerCAmelCase = json.load(_SCREAMING_SNAKE_CASE ) lowerCAmelCase = """MLukeTokenizer""" with open(os.path.join(_SCREAMING_SNAKE_CASE , """tokenizer_config.json""" ) , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , MLukeTokenizer.vocab_files_names["""entity_vocab_file"""] ) , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase = MLukeTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) # Initialize the embeddings of the special tokens lowerCAmelCase = tokenizer.convert_tokens_to_ids(["""@"""] )[0] lowerCAmelCase = tokenizer.convert_tokens_to_ids(["""#"""] )[0] lowerCAmelCase = state_dict["""embeddings.word_embeddings.weight"""] lowerCAmelCase = word_emb[ent_init_index].unsqueeze(0 ) lowerCAmelCase = word_emb[enta_init_index].unsqueeze(0 ) lowerCAmelCase = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: lowerCAmelCase = state_dict[bias_name] lowerCAmelCase = decoder_bias[ent_init_index].unsqueeze(0 ) lowerCAmelCase = decoder_bias[enta_init_index].unsqueeze(0 ) lowerCAmelCase = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: lowerCAmelCase = f'encoder.layer.{layer_index}.attention.self.' lowerCAmelCase = state_dict[prefix + matrix_name] lowerCAmelCase = state_dict[prefix + matrix_name] lowerCAmelCase = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks lowerCAmelCase = state_dict["""entity_embeddings.entity_embeddings.weight"""] lowerCAmelCase = entity_emb[entity_vocab["""[MASK]"""]].unsqueeze(0 ) lowerCAmelCase = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' lowerCAmelCase = state_dict["""entity_predictions.bias"""] lowerCAmelCase = entity_prediction_bias[entity_vocab["""[MASK]"""]].unsqueeze(0 ) lowerCAmelCase = torch.cat([entity_prediction_bias, entity_mask_bias] ) lowerCAmelCase = LukeForMaskedLM(config=_SCREAMING_SNAKE_CASE ).eval() state_dict.pop("""entity_predictions.decoder.weight""" ) state_dict.pop("""lm_head.decoder.weight""" ) state_dict.pop("""lm_head.decoder.bias""" ) lowerCAmelCase = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("""lm_head""" ) or key.startswith("""entity_predictions""" )): lowerCAmelCase = state_dict[key] else: lowerCAmelCase = state_dict[key] lowerCAmelCase, lowerCAmelCase = model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) if set(_SCREAMING_SNAKE_CASE ) != {"luke.embeddings.position_ids"}: raise ValueError(f'Unexpected unexpected_keys: {unexpected_keys}' ) if set(_SCREAMING_SNAKE_CASE ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f'Unexpected missing_keys: {missing_keys}' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs lowerCAmelCase = MLukeTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE , task="""entity_classification""" ) lowerCAmelCase = """ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).""" lowerCAmelCase = (0, 9) lowerCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , entity_spans=[span] , return_tensors="""pt""" ) lowerCAmelCase = model(**_SCREAMING_SNAKE_CASE ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base lowerCAmelCase = torch.Size((1, 33, 768) ) lowerCAmelCase = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base lowerCAmelCase = torch.Size((1, 1, 768) ) lowerCAmelCase = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' f' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction lowerCAmelCase = MLukeTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) lowerCAmelCase = """Tokyo is the capital of <mask>.""" lowerCAmelCase = (24, 30) lowerCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , entity_spans=[span] , return_tensors="""pt""" ) lowerCAmelCase = model(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase = encoding["""input_ids"""][0].tolist() lowerCAmelCase = input_ids.index(tokenizer.convert_tokens_to_ids("""<mask>""" ) ) lowerCAmelCase = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(_SCREAMING_SNAKE_CASE ) lowerCAmelCase = outputs.entity_logits[0][0].argmax().item() lowerCAmelCase = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("""en:""" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("""Saving PyTorch model to {}""".format(_SCREAMING_SNAKE_CASE ) ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def _snake_case ( _SCREAMING_SNAKE_CASE : Dict ) -> List[str]: """simple docstring""" lowerCAmelCase = ["""[MASK]""", """[PAD]""", """[UNK]"""] lowerCAmelCase = [json.loads(_SCREAMING_SNAKE_CASE ) for line in open(_SCREAMING_SNAKE_CASE )] lowerCAmelCase = {} for entry in data: lowerCAmelCase = entry["""id"""] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: lowerCAmelCase = entity_id break lowerCAmelCase = f'{language}:{entity_name}' lowerCAmelCase = entity_id return new_mapping if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) UpperCAmelCase = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
356
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip UpperCAmelCase = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def _snake_case ( _SCREAMING_SNAKE_CASE : Tuple ) -> List[Any]: """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def _snake_case ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str ) -> Dict: """simple docstring""" return max(metric_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def _snake_case ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: """simple docstring""" lowerCAmelCase = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , """r""" ).readlines()] lowerCAmelCase = [] if args.gold_data_mode == "qa": lowerCAmelCase = pd.read_csv(_SCREAMING_SNAKE_CASE , sep="""\t""" , header=_SCREAMING_SNAKE_CASE ) for answer_list in data[1]: lowerCAmelCase = ast.literal_eval(_SCREAMING_SNAKE_CASE ) answers.append(_SCREAMING_SNAKE_CASE ) else: lowerCAmelCase = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , """r""" ).readlines()] lowerCAmelCase = [[reference] for reference in references] lowerCAmelCase = lowerCAmelCase = lowerCAmelCase = 0 for prediction, ground_truths in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCAmelCase = 100.0 * em / total lowerCAmelCase = 100.0 * fa / total logger.info(f'F1: {fa:.2f}' ) logger.info(f'EM: {em:.2f}' ) def _snake_case ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Dict ) -> Optional[Any]: """simple docstring""" lowerCAmelCase = args.k lowerCAmelCase = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , """r""" ).readlines()] lowerCAmelCase = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , """r""" ).readlines()] lowerCAmelCase = lowerCAmelCase = 0 for hypo, reference in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase = set(hypo.split("""\t""" )[:k] ) lowerCAmelCase = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k lowerCAmelCase = 100.0 * em / total logger.info(f'Precision@{k}: {em: .2f}' ) def _snake_case ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] ) -> Any: """simple docstring""" def strip_title(_SCREAMING_SNAKE_CASE : Union[str, Any] ): if title.startswith("""\"""" ): lowerCAmelCase = title[1:] if title.endswith("""\"""" ): lowerCAmelCase = title[:-1] return title lowerCAmelCase = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , )["""input_ids"""].to(args.device ) lowerCAmelCase = rag_model.rag.question_encoder(_SCREAMING_SNAKE_CASE ) lowerCAmelCase = question_enc_outputs[0] lowerCAmelCase = rag_model.retriever( _SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) lowerCAmelCase = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) lowerCAmelCase = [] for docs in all_docs: lowerCAmelCase = [strip_title(_SCREAMING_SNAKE_CASE ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(_SCREAMING_SNAKE_CASE ) ) return provenance_strings def _snake_case ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : str ) -> Tuple: """simple docstring""" with torch.no_grad(): lowerCAmelCase = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) lowerCAmelCase = inputs_dict.input_ids.to(args.device ) lowerCAmelCase = inputs_dict.attention_mask.to(args.device ) lowerCAmelCase = rag_model.generate( # rag_model overwrites generate _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=_SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) lowerCAmelCase = rag_model.retriever.generator_tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): logger.info("""Q: {} - A: {}""".format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) return answers def _snake_case ( ) -> Dict: """simple docstring""" lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=_SCREAMING_SNAKE_CASE , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=_SCREAMING_SNAKE_CASE , choices=["""exact""", """compressed""", """legacy"""] , type=_SCREAMING_SNAKE_CASE , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=_SCREAMING_SNAKE_CASE , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=_SCREAMING_SNAKE_CASE , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=_SCREAMING_SNAKE_CASE , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=_SCREAMING_SNAKE_CASE , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=_SCREAMING_SNAKE_CASE , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=_SCREAMING_SNAKE_CASE , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=_SCREAMING_SNAKE_CASE , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=_SCREAMING_SNAKE_CASE , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=_SCREAMING_SNAKE_CASE , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) lowerCAmelCase = parser.parse_args() lowerCAmelCase = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def _snake_case ( _SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[Any]: """simple docstring""" lowerCAmelCase = {} if args.model_type is None: lowerCAmelCase = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): lowerCAmelCase = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration lowerCAmelCase = args.n_docs if args.index_name is not None: lowerCAmelCase = args.index_name if args.index_path is not None: lowerCAmelCase = args.index_path else: lowerCAmelCase = BartForConditionalGeneration lowerCAmelCase = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , _SCREAMING_SNAKE_CASE ) lowerCAmelCase = get_scores if args.eval_mode == """e2e""" else get_precision_at_k lowerCAmelCase = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(_SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(_SCREAMING_SNAKE_CASE ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): lowerCAmelCase = RagRetriever.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCAmelCase = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , retriever=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: lowerCAmelCase = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: lowerCAmelCase = [] for line in tqdm(_SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(_SCREAMING_SNAKE_CASE ) == args.eval_batch_size: lowerCAmelCase = evaluate_batch_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(_SCREAMING_SNAKE_CASE ) + """\n""" ) preds_file.flush() lowerCAmelCase = [] if len(_SCREAMING_SNAKE_CASE ) > 0: lowerCAmelCase = evaluate_batch_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) preds_file.write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(_SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": UpperCAmelCase = get_args() main(args)
187
0
"""simple docstring""" import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = BertJapaneseTokenizer __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Any = True def __UpperCAmelCase ( self ): super().setUp() __a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは''', '''世界''', '''##世界''', '''、''', '''##、''', '''。''', '''##。''', ] __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __UpperCAmelCase ( self , _a ): __a = '''こんにちは、世界。 \nこんばんは、世界。''' __a = '''こんにちは 、 世界 。 こんばんは 、 世界 。''' return input_text, output_text def __UpperCAmelCase ( self , _a ): __a , __a = self.get_input_output_texts(_a ) __a = tokenizer.encode(_a , add_special_tokens=_a ) __a = tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) return text, ids def __UpperCAmelCase ( self ): pass # TODO add if relevant def __UpperCAmelCase ( self ): pass # TODO add if relevant def __UpperCAmelCase ( self ): pass # TODO add if relevant def __UpperCAmelCase ( self ): __a = self.tokenizer_class(self.vocab_file ) __a = tokenizer.tokenize('''こんにちは、世界。\nこんばんは、世界。''' ) self.assertListEqual(_a , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def __UpperCAmelCase ( self ): __a = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''mecab''' ) self.assertIsNotNone(_a ) __a = '''こんにちは、世界。\nこんばんは、世界。''' __a = tokenizer.tokenize(_a ) self.assertListEqual(_a , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) __a = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(_a , '''wb''' ) as handle: pickle.dump(_a , _a ) with open(_a , '''rb''' ) as handle: __a = pickle.load(_a ) __a = tokenizer_new.tokenize(_a ) self.assertListEqual(_a , _a ) def __UpperCAmelCase ( self ): __a = MecabTokenizer(mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __UpperCAmelCase ( self ): try: __a = MecabTokenizer(mecab_dic='''unidic_lite''' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __UpperCAmelCase ( self ): try: __a = MecabTokenizer(mecab_dic='''unidic''' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __UpperCAmelCase ( self ): __a = MecabTokenizer(do_lower_case=_a , mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iphone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __UpperCAmelCase ( self ): try: __a = MecabTokenizer( do_lower_case=_a , normalize_text=_a , mecab_option='''-d /usr/local/lib/mecab/dic/jumandic''' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) def __UpperCAmelCase ( self ): __a = MecabTokenizer(normalize_text=_a , mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。'''] , ) @require_sudachi def __UpperCAmelCase ( self ): __a = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''sudachi''' ) self.assertIsNotNone(_a ) __a = '''こんにちは、世界。\nこんばんは、世界。''' __a = tokenizer.tokenize(_a ) self.assertListEqual(_a , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) __a = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(_a , '''wb''' ) as handle: pickle.dump(_a , _a ) with open(_a , '''rb''' ) as handle: __a = pickle.load(_a ) __a = tokenizer_new.tokenize(_a ) self.assertListEqual(_a , _a ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''A''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国''', '''人''', '''参政''', '''権'''] ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''B''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人''', '''参政権'''] ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''C''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人参政権'''] ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(do_lower_case=_a , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(normalize_text=_a , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', '''\u3000''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __UpperCAmelCase ( self ): __a = SudachiTokenizer(trim_whitespace=_a , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) @require_jumanpp def __UpperCAmelCase ( self ): __a = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''jumanpp''' ) self.assertIsNotNone(_a ) __a = '''こんにちは、世界。\nこんばんは、世界。''' __a = tokenizer.tokenize(_a ) self.assertListEqual(_a , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) __a = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(_a , '''wb''' ) as handle: pickle.dump(_a , _a ) with open(_a , '''rb''' ) as handle: __a = pickle.load(_a ) __a = tokenizer_new.tokenize(_a ) self.assertListEqual(_a , _a ) @require_jumanpp def __UpperCAmelCase ( self ): __a = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __UpperCAmelCase ( self ): __a = JumanppTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __UpperCAmelCase ( self ): __a = JumanppTokenizer(normalize_text=_a ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''ア''', '''ッ''', '''フ''', '''゚''', '''ル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __UpperCAmelCase ( self ): __a = JumanppTokenizer(trim_whitespace=_a ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''。'''] , ) @require_jumanpp def __UpperCAmelCase ( self ): __a = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('''ありがとうございますm(_ _)m見つけるのが大変です。''' ) , ['''ありがとう''', '''ございます''', '''m(_ _)m''', '''見つける''', '''の''', '''が''', '''大変です''', '''。'''] , ) def __UpperCAmelCase ( self ): __a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは'''] __a = {} for i, token in enumerate(_a ): __a = i __a = WordpieceTokenizer(vocab=_a , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こんにちは'''] ) self.assertListEqual(tokenizer.tokenize('''こんばんは''' ) , ['''こん''', '''##ばんは'''] ) self.assertListEqual(tokenizer.tokenize('''こんばんは こんばんにちは こんにちは''' ) , ['''こん''', '''##ばんは''', '''[UNK]''', '''こんにちは'''] ) def __UpperCAmelCase ( self ): __a = BertJapaneseTokenizer.from_pretrained('''nlp-waseda/roberta-base-japanese-with-auto-jumanpp''' ) __a = tokenizer.subword_tokenizer __a = subword_tokenizer.tokenize('''国境 の 長い トンネル を 抜ける と 雪国 であった 。''' ) self.assertListEqual(_a , ['''▁国境''', '''▁の''', '''▁長い''', '''▁トンネル''', '''▁を''', '''▁抜ける''', '''▁と''', '''▁雪''', '''国''', '''▁であった''', '''▁。'''] ) __a = subword_tokenizer.tokenize('''こんばんは こんばん にち は こんにちは''' ) self.assertListEqual(_a , ['''▁こん''', '''ばん''', '''は''', '''▁こん''', '''ばん''', '''▁に''', '''ち''', '''▁は''', '''▁こんにちは'''] ) def __UpperCAmelCase ( self ): __a = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese''' ) __a = tokenizer.encode('''ありがとう。''' , add_special_tokens=_a ) __a = tokenizer.encode('''どういたしまして。''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Dict = BertJapaneseTokenizer __UpperCAmelCase : Any = False def __UpperCAmelCase ( self ): super().setUp() __a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。'''] __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __UpperCAmelCase ( self , **_a ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='''character''' , **_a ) def __UpperCAmelCase ( self , _a ): __a = '''こんにちは、世界。 \nこんばんは、世界。''' __a = '''こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。''' return input_text, output_text def __UpperCAmelCase ( self ): pass # TODO add if relevant def __UpperCAmelCase ( self ): pass # TODO add if relevant def __UpperCAmelCase ( self ): pass # TODO add if relevant def __UpperCAmelCase ( self ): __a = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='''character''' ) __a = tokenizer.tokenize('''こんにちは、世界。 \nこんばんは、世界。''' ) self.assertListEqual( _a , ['''こ''', '''ん''', '''に''', '''ち''', '''は''', '''、''', '''世''', '''界''', '''。''', '''こ''', '''ん''', '''ば''', '''ん''', '''は''', '''、''', '''世''', '''界''', '''。'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def __UpperCAmelCase ( self ): __a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。'''] __a = {} for i, token in enumerate(_a ): __a = i __a = CharacterTokenizer(vocab=_a , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''は'''] ) self.assertListEqual(tokenizer.tokenize('''こんにちほ''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''[UNK]'''] ) def __UpperCAmelCase ( self ): __a = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese-char''' ) __a = tokenizer.encode('''ありがとう。''' , add_special_tokens=_a ) __a = tokenizer.encode('''どういたしまして。''' , add_special_tokens=_a ) __a = tokenizer.build_inputs_with_special_tokens(_a ) __a = tokenizer.build_inputs_with_special_tokens(_a , _a ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = '''cl-tohoku/bert-base-japanese''' __a = AutoTokenizer.from_pretrained(_a ) self.assertIsInstance(_a , _a ) class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = '''cl-tohoku/bert-base-japanese''' with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm: BertTokenizer.from_pretrained(_a ) self.assertTrue( cm.records[0].message.startswith( '''The tokenizer class you load from this checkpoint is not the same type as the class this function''' ''' is called from.''' ) ) __a = '''bert-base-cased''' with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm: BertJapaneseTokenizer.from_pretrained(_a ) self.assertTrue( cm.records[0].message.startswith( '''The tokenizer class you load from this checkpoint is not the same type as the class this function''' ''' is called from.''' ) )
45
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
1
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { """facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""", """facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""", } class lowerCamelCase_ ( _A ): '''simple docstring''' a__ = "encodec" def __init__( self : Optional[Any] , __lowerCamelCase : Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , __lowerCamelCase : Dict=2_40_00 , __lowerCamelCase : Union[str, Any]=1 , __lowerCamelCase : List[str]=False , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : Tuple=1_28 , __lowerCamelCase : int=32 , __lowerCamelCase : str=1 , __lowerCamelCase : Dict=[8, 5, 4, 2] , __lowerCamelCase : List[str]="weight_norm" , __lowerCamelCase : List[Any]=7 , __lowerCamelCase : Union[str, Any]=7 , __lowerCamelCase : str=3 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Any=True , __lowerCamelCase : Optional[int]="reflect" , __lowerCamelCase : List[str]=2 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Optional[int]=1.0 , __lowerCamelCase : Tuple=10_24 , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Dict=True , **__lowerCamelCase : Dict , ) -> Optional[int]: A : Optional[Any] = target_bandwidths A : Dict = sampling_rate A : int = audio_channels A : Tuple = normalize A : str = chunk_length_s A : Union[str, Any] = overlap A : str = hidden_size A : Optional[Any] = num_filters A : Optional[int] = num_residual_layers A : Dict = upsampling_ratios A : str = norm_type A : Tuple = kernel_size A : Dict = last_kernel_size A : Union[str, Any] = residual_kernel_size A : int = dilation_growth_rate A : Tuple = use_causal_conv A : Optional[int] = pad_mode A : List[Any] = compress A : Optional[Any] = num_lstm_layers A : Optional[int] = trim_right_ratio A : int = codebook_size A : str = codebook_dim if codebook_dim is not None else hidden_size A : Optional[int] = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**__lowerCamelCase ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]: if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[int]: if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> int: A : Any = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
256
from collections.abc import Generator from math import sin def UpperCAmelCase ( _lowerCamelCase ): if len(_lowerCamelCase ) != 32: raise ValueError("Input must be of length 32" ) A : Any = B"" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def UpperCAmelCase ( _lowerCamelCase ): if i < 0: raise ValueError("Input must be non-negative" ) A : List[Any] = format(_lowerCamelCase , "08x" )[-8:] A : List[str] = B"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8" ) return little_endian_hex def UpperCAmelCase ( _lowerCamelCase ): A : Optional[Any] = B"" for char in message: bit_string += format(_lowerCamelCase , "08b" ).encode("utf-8" ) A : int = format(len(_lowerCamelCase ) , "064b" ).encode("utf-8" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_lowerCamelCase ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def UpperCAmelCase ( _lowerCamelCase ): if len(_lowerCamelCase ) % 512 != 0: raise ValueError("Input must have length that's a multiple of 512" ) for pos in range(0 , len(_lowerCamelCase ) , 512 ): A : Optional[int] = bit_string[pos : pos + 512] A : List[str] = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def UpperCAmelCase ( _lowerCamelCase ): if i < 0: raise ValueError("Input must be non-negative" ) A : Union[str, Any] = format(_lowerCamelCase , "032b" ) A : List[str] = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(_lowerCamelCase , 2 ) def UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase ): return (a + b) % 2**32 def UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase ): if i < 0: raise ValueError("Input must be non-negative" ) if shift < 0: raise ValueError("Shift must be non-negative" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def UpperCAmelCase ( _lowerCamelCase ): A : Union[str, Any] = preprocess(_lowerCamelCase ) A : Any = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states A : Optional[int] = 0X67452301 A : Any = 0Xefcdab89 A : Tuple = 0X98badcfe A : Union[str, Any] = 0X10325476 A : Optional[Any] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_lowerCamelCase ): A : Optional[Any] = aa A : Optional[Any] = ba A : List[Any] = ca A : Optional[int] = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f A : Dict = d ^ (b & (c ^ d)) A : Optional[Any] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f A : Optional[int] = c ^ (d & (b ^ c)) A : List[Any] = (5 * i + 1) % 16 elif i <= 47: A : Tuple = b ^ c ^ d A : str = (3 * i + 5) % 16 else: A : Union[str, Any] = c ^ (b | not_aa(_lowerCamelCase )) A : Any = (7 * i) % 16 A : Union[str, Any] = (f + a + added_consts[i] + block_words[g]) % 2**32 A : Dict = d A : Optional[int] = c A : Optional[int] = b A : Any = sum_aa(_lowerCamelCase , left_rotate_aa(_lowerCamelCase , shift_amounts[i] ) ) # Add hashed chunk to running total A : Dict = sum_aa(_lowerCamelCase , _lowerCamelCase ) A : Any = sum_aa(_lowerCamelCase , _lowerCamelCase ) A : Dict = sum_aa(_lowerCamelCase , _lowerCamelCase ) A : Union[str, Any] = sum_aa(_lowerCamelCase , _lowerCamelCase ) A : Optional[Any] = reformat_hex(_lowerCamelCase ) + reformat_hex(_lowerCamelCase ) + reformat_hex(_lowerCamelCase ) + reformat_hex(_lowerCamelCase ) return digest if __name__ == "__main__": import doctest doctest.testmod()
256
1
import argparse import collections import json import os import re import string import sys import numpy as np lowerCAmelCase = re.compile(R'\b(a|an|the)\b', re.UNICODE) lowerCAmelCase = None def _a ( ): """simple docstring""" lowercase__ = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=SCREAMING_SNAKE_CASE , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=SCREAMING_SNAKE_CASE , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowercase__ = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" def remove_articles(SCREAMING_SNAKE_CASE ): return ARTICLES_REGEX.sub(''' ''' , SCREAMING_SNAKE_CASE ) def white_space_fix(SCREAMING_SNAKE_CASE ): return " ".join(text.split() ) def remove_punc(SCREAMING_SNAKE_CASE ): lowercase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(SCREAMING_SNAKE_CASE ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE ) ) ) ) def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" if not s: return [] return normalize_answer(SCREAMING_SNAKE_CASE ).split() def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" return int(normalize_answer(SCREAMING_SNAKE_CASE ) == normalize_answer(SCREAMING_SNAKE_CASE ) ) def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = get_tokens(SCREAMING_SNAKE_CASE ) lowercase__ = get_tokens(SCREAMING_SNAKE_CASE ) lowercase__ = collections.Counter(SCREAMING_SNAKE_CASE ) & collections.Counter(SCREAMING_SNAKE_CASE ) lowercase__ = sum(common.values() ) if len(SCREAMING_SNAKE_CASE ) == 0 or len(SCREAMING_SNAKE_CASE ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 lowercase__ = 1.0 * num_same / len(SCREAMING_SNAKE_CASE ) lowercase__ = 1.0 * num_same / len(SCREAMING_SNAKE_CASE ) lowercase__ = (2 * precision * recall) / (precision + recall) return fa def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = {} lowercase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowercase__ = qa['''id'''] lowercase__ = [t for t in qa['''answers''']['''text'''] if normalize_answer(SCREAMING_SNAKE_CASE )] if not gold_answers: # For unanswerable questions, only correct answer is empty string lowercase__ = [''''''] if qid not in preds: print(f'Missing prediction for {qid}' ) continue lowercase__ = preds[qid] # Take max over all gold answers lowercase__ = max(compute_exact(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for a in gold_answers ) lowercase__ = max(compute_fa(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for a in gold_answers ) return exact_scores, fa_scores def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = {} for qid, s in scores.items(): lowercase__ = na_probs[qid] > na_prob_thresh if pred_na: lowercase__ = float(not qid_to_has_ans[qid] ) else: lowercase__ = s return new_scores def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None ): """simple docstring""" if not qid_list: lowercase__ = len(SCREAMING_SNAKE_CASE ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: lowercase__ = len(SCREAMING_SNAKE_CASE ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" for k in new_eval: lowercase__ = new_eval[k] def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" plt.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(SCREAMING_SNAKE_CASE ) plt.savefig(SCREAMING_SNAKE_CASE ) plt.clf() def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase__ = sorted(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE : na_probs[k] ) lowercase__ = 0.0 lowercase__ = 1.0 lowercase__ = 0.0 lowercase__ = [1.0] lowercase__ = [0.0] lowercase__ = 0.0 for i, qid in enumerate(SCREAMING_SNAKE_CASE ): if qid_to_has_ans[qid]: true_pos += scores[qid] lowercase__ = true_pos / float(i + 1 ) lowercase__ = true_pos / float(SCREAMING_SNAKE_CASE ) if i == len(SCREAMING_SNAKE_CASE ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(SCREAMING_SNAKE_CASE ) recalls.append(SCREAMING_SNAKE_CASE ) if out_image: plot_pr_curve(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return {"ap": 100.0 * avg_prec} def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" if out_image_dir and not os.path.exists(SCREAMING_SNAKE_CASE ): os.makedirs(SCREAMING_SNAKE_CASE ) lowercase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return lowercase__ = make_precision_recall_eval( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , out_image=os.path.join(SCREAMING_SNAKE_CASE , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) lowercase__ = make_precision_recall_eval( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , out_image=os.path.join(SCREAMING_SNAKE_CASE , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) lowercase__ = {k: float(SCREAMING_SNAKE_CASE ) for k, v in qid_to_has_ans.items()} lowercase__ = make_precision_recall_eval( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , out_image=os.path.join(SCREAMING_SNAKE_CASE , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''pr_exact''' ) merge_eval(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''pr_f1''' ) merge_eval(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''pr_oracle''' ) def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" if not qid_list: return lowercase__ = [na_probs[k] for k in qid_list] lowercase__ = np.ones_like(SCREAMING_SNAKE_CASE ) / float(len(SCREAMING_SNAKE_CASE ) ) plt.hist(SCREAMING_SNAKE_CASE , weights=SCREAMING_SNAKE_CASE , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'Histogram of no-answer probability: {name}' ) plt.savefig(os.path.join(SCREAMING_SNAKE_CASE , f'na_prob_hist_{name}.png' ) ) plt.clf() def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) lowercase__ = num_no_ans lowercase__ = cur_score lowercase__ = 0.0 lowercase__ = sorted(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE : na_probs[k] ) for i, qid in enumerate(SCREAMING_SNAKE_CASE ): if qid not in scores: continue if qid_to_has_ans[qid]: lowercase__ = scores[qid] else: if preds[qid]: lowercase__ = -1 else: lowercase__ = 0 cur_score += diff if cur_score > best_score: lowercase__ = cur_score lowercase__ = na_probs[qid] return 100.0 * best_score / len(SCREAMING_SNAKE_CASE ), best_thresh def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ , lowercase__ = find_best_thresh(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ , lowercase__ = find_best_thresh(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ = best_exact lowercase__ = exact_thresh lowercase__ = best_fa lowercase__ = fa_thresh def _a ( ): """simple docstring""" with open(OPTS.data_file ) as f: lowercase__ = json.load(SCREAMING_SNAKE_CASE ) lowercase__ = dataset_json['''data'''] with open(OPTS.pred_file ) as f: lowercase__ = json.load(SCREAMING_SNAKE_CASE ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: lowercase__ = json.load(SCREAMING_SNAKE_CASE ) else: lowercase__ = {k: 0.0 for k in preds} lowercase__ = make_qid_to_has_ans(SCREAMING_SNAKE_CASE ) # maps qid to True/False lowercase__ = [k for k, v in qid_to_has_ans.items() if v] lowercase__ = [k for k, v in qid_to_has_ans.items() if not v] lowercase__ , lowercase__ = get_raw_scores(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ = apply_no_ans_threshold(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , OPTS.na_prob_thresh ) lowercase__ = apply_no_ans_threshold(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , OPTS.na_prob_thresh ) lowercase__ = make_eval_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if has_ans_qids: lowercase__ = make_eval_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , qid_list=SCREAMING_SNAKE_CASE ) merge_eval(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''HasAns''' ) if no_ans_qids: lowercase__ = make_eval_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , qid_list=SCREAMING_SNAKE_CASE ) merge_eval(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , OPTS.out_image_dir ) histogram_na_prob(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: print(json.dumps(SCREAMING_SNAKE_CASE , indent=2 ) ) if __name__ == "__main__": lowerCAmelCase = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
110
from __future__ import annotations from collections.abc import Iterator class _a : def __init__( self: List[str] , UpperCamelCase_: int ) -> None: """simple docstring""" lowercase__ = value lowercase__ = None lowercase__ = None class _a : def __init__( self: Union[str, Any] , UpperCamelCase_: Node ) -> None: """simple docstring""" lowercase__ = tree def lowerCamelCase_ ( self: Any , UpperCamelCase_: Node | None ) -> int: """simple docstring""" if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self: List[str] ) -> Iterator[int]: """simple docstring""" yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
110
1
'''simple docstring''' from collections.abc import Sequence def a_ ( _UpperCAmelCase : Sequence[float] ,_UpperCAmelCase : float ) -> Any: return sum(c * (x**i) for i, c in enumerate(lowerCAmelCase__ ) ) def a_ ( _UpperCAmelCase : Sequence[float] ,_UpperCAmelCase : float ) -> Any: __snake_case : str = 0.0 for coeff in reversed(lowerCAmelCase__ ): __snake_case : Dict = result * x + coeff return result if __name__ == "__main__": A__ : List[Any] = (0.0, 0.0, 5.0, 9.3, 7.0) A__ : List[Any] = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
351
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
0
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(__SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Base Case if index == len(__SCREAMING_SNAKE_CASE ): return True # Recursive Step for i in range(__SCREAMING_SNAKE_CASE ): if valid_coloring(graph[index] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Color current vertex lowercase = i # Validate coloring if util_color(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , index + 1 ): return True # Backtrack lowercase = -1 return False def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = [-1] * len(__SCREAMING_SNAKE_CASE ) if util_color(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 0 ): return colored_vertices return []
195
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class A_ ( __lowerCamelCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(snake_case , 'hidden_sizes' ) ) self.parent.assertTrue(hasattr(snake_case , 'num_attention_heads' ) ) class A_ : '''simple docstring''' def __init__( self , snake_case , snake_case=13 , snake_case=64 , snake_case=3 , snake_case=3 , snake_case=2 , snake_case=1 , snake_case=16 , snake_case=[128, 256, 384] , snake_case=[4, 6, 8] , snake_case=[2, 3, 4] , snake_case=[16, 16, 16] , snake_case=0 , snake_case=[2, 2, 2] , snake_case=[2, 2, 2] , snake_case=0.02 , snake_case=True , snake_case=True , snake_case=2 , ): lowercase = parent lowercase = batch_size lowercase = image_size lowercase = num_channels lowercase = kernel_size lowercase = stride lowercase = padding lowercase = hidden_sizes lowercase = num_attention_heads lowercase = depths lowercase = key_dim lowercase = drop_path_rate lowercase = patch_size lowercase = attention_ratio lowercase = mlp_ratio lowercase = initializer_range lowercase = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] lowercase = is_training lowercase = use_labels lowercase = num_labels lowercase = initializer_range def SCREAMING_SNAKE_CASE__ ( self ): lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase = None if self.use_labels: lowercase = ids_tensor([self.batch_size] , self.num_labels ) lowercase = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case ): lowercase = LevitModel(config=snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case ) lowercase = (self.image_size, self.image_size) lowercase , lowercase = image_size[0], image_size[1] for _ in range(4 ): lowercase = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) lowercase = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case ): lowercase = self.num_labels lowercase = LevitForImageClassification(snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.prepare_config_and_inputs() lowercase , lowercase , lowercase = config_and_inputs lowercase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A_ ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): '''simple docstring''' _UpperCamelCase : Tuple = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) _UpperCamelCase : Dict = ( { """feature-extraction""": LevitModel, """image-classification""": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) _UpperCamelCase : Dict = False _UpperCamelCase : List[str] = False _UpperCamelCase : List[str] = False _UpperCamelCase : str = False _UpperCamelCase : List[str] = False def SCREAMING_SNAKE_CASE__ ( self ): lowercase = LevitModelTester(self ) lowercase = ConfigTester(self , config_class=snake_case , has_text_modality=snake_case , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self ): return @unittest.skip(reason='Levit does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE__ ( self ): pass @unittest.skip(reason='Levit does not support input and output embeddings' ) def SCREAMING_SNAKE_CASE__ ( self ): pass @unittest.skip(reason='Levit does not output attentions' ) def SCREAMING_SNAKE_CASE__ ( self ): pass def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase = model_class(snake_case ) lowercase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase = [*signature.parameters.keys()] lowercase = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): def check_hidden_states_output(snake_case , snake_case , snake_case ): lowercase = model_class(snake_case ) model.to(snake_case ) model.eval() with torch.no_grad(): lowercase = model(**self._prepare_for_class(snake_case , snake_case ) ) lowercase = outputs.hidden_states lowercase = len(self.model_tester.depths ) + 1 self.assertEqual(len(snake_case ) , snake_case ) lowercase = (self.model_tester.image_size, self.model_tester.image_size) lowercase , lowercase = image_size[0], image_size[1] for _ in range(4 ): lowercase = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) lowercase = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase = True check_hidden_states_output(snake_case , snake_case , snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase = True check_hidden_states_output(snake_case , snake_case , snake_case ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def SCREAMING_SNAKE_CASE__ ( self ): pass def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case=False ): lowercase = super()._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): if not self.model_tester.is_training: return lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(snake_case ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue lowercase = model_class(snake_case ) model.to(snake_case ) model.train() lowercase = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) lowercase = model(**snake_case ).loss loss.backward() def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return lowercase = False lowercase = True for model_class in self.all_model_classes: if model_class in get_values(snake_case ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue lowercase = model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() lowercase = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) lowercase = model(**snake_case ).loss loss.backward() def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(snake_case ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): lowercase = problem_type['title'] lowercase = problem_type['num_labels'] lowercase = model_class(snake_case ) model.to(snake_case ) model.train() lowercase = self._prepare_for_class(snake_case , snake_case , return_labels=snake_case ) if problem_type["num_labels"] > 1: lowercase = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) lowercase = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=snake_case ) as warning_list: lowercase = model(**snake_case ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def SCREAMING_SNAKE_CASE__ ( self ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase = LevitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def UpperCAmelCase_ ( ): lowercase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def SCREAMING_SNAKE_CASE__ ( self ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( snake_case ) lowercase = self.default_image_processor lowercase = prepare_img() lowercase = image_processor(images=snake_case , return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): lowercase = model(**snake_case ) # verify the logits lowercase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , snake_case ) lowercase = torch.tensor([1.0_448, -0.3_745, -1.8_317] ).to(snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case , atol=1E-4 ) )
195
1
'''simple docstring''' from collections import deque class lowerCamelCase_ : def __init__( self : str , _A : str , _A : int , _A : int ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = process_name # process name UpperCAmelCase__ : Optional[int] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time UpperCAmelCase__ : str = arrival_time UpperCAmelCase__ : List[Any] = burst_time # remaining burst time UpperCAmelCase__ : Any = 0 # total time of the process wait in ready queue UpperCAmelCase__ : Tuple = 0 # time from arrival time to completion time class lowerCamelCase_ : def __init__( self : List[str] , _A : int , _A : list[int] , _A : deque[Process] , _A : int , ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = number_of_queues # time slice of queues that round robin algorithm applied UpperCAmelCase__ : List[str] = time_slices # unfinished process is in this ready_queue UpperCAmelCase__ : List[str] = queue # current time UpperCAmelCase__ : Optional[Any] = current_time # finished process is in this sequence queue UpperCAmelCase__ : deque[Process] = deque() def lowercase_ ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def lowercase_ ( self : Tuple , _A : list[Process] ): '''simple docstring''' UpperCAmelCase__ : Tuple = [] for i in range(len(_A ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def lowercase_ ( self : Union[str, Any] , _A : list[Process] ): '''simple docstring''' UpperCAmelCase__ : int = [] for i in range(len(_A ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def lowercase_ ( self : Optional[int] , _A : list[Process] ): '''simple docstring''' UpperCAmelCase__ : Tuple = [] for i in range(len(_A ) ): completion_times.append(queue[i].stop_time ) return completion_times def lowercase_ ( self : str , _A : deque[Process] ): '''simple docstring''' return [q.burst_time for q in queue] def lowercase_ ( self : int , _A : Process ): '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def lowercase_ ( self : Optional[int] , _A : deque[Process] ): '''simple docstring''' UpperCAmelCase__ : deque[Process] = deque() # sequence deque of finished process while len(_A ) != 0: UpperCAmelCase__ : List[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(_A ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 UpperCAmelCase__ : Optional[int] = 0 # set the process's turnaround time because it is finished UpperCAmelCase__ : Union[str, Any] = self.current_time - cp.arrival_time # set the completion time UpperCAmelCase__ : Any = self.current_time # add the process to queue that has finished queue finished.append(_A ) self.finish_queue.extend(_A ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def lowercase_ ( self : str , _A : deque[Process] , _A : int ): '''simple docstring''' UpperCAmelCase__ : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(_A ) ): UpperCAmelCase__ : 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(_A ) # 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 UpperCAmelCase__ : List[str] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(_A ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished UpperCAmelCase__ : Any = 0 # set the finish time UpperCAmelCase__ : int = self.current_time # update the process' turnaround time because it is finished UpperCAmelCase__ : Dict = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(_A ) self.finish_queue.extend(_A ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def lowercase_ ( self : Dict ): '''simple docstring''' for i in range(self.number_of_queues - 1 ): UpperCAmelCase__ : 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, 5_3) UpperCamelCase__ = Process('''P2''', 0, 1_7) UpperCamelCase__ = Process('''P3''', 0, 6_8) UpperCamelCase__ = Process('''P4''', 0, 2_4) UpperCamelCase__ = 3 UpperCamelCase__ = [1_7, 2_5] 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, 5_3) UpperCamelCase__ = Process('''P2''', 0, 1_7) UpperCamelCase__ = Process('''P3''', 0, 6_8) UpperCamelCase__ = Process('''P4''', 0, 2_4) UpperCamelCase__ = 3 UpperCamelCase__ = [1_7, 2_5] 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()}""" )
351
'''simple docstring''' from __future__ import annotations import math def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if not scores: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , minimax(depth + 1 , node_index * 2 + 1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , minimax(depth + 1 , node_index * 2 + 1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , ) ) def a__ ( ) -> None: UpperCAmelCase__ : Union[str, Any] = [90, 23, 6, 33, 21, 65, 1_23, 3_44_23] UpperCAmelCase__ : Optional[Any] = math.log(len(lowerCAmelCase__ ) , 2 ) print(F"""Optimal value : {minimax(0 , 0 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )}""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
299
0
import os from typing import Dict, List, Tuple, TypeVar, Union lowercase__ : Dict = TypeVar("T") lowercase__ : Optional[int] = Union[List[T], Tuple[T, ...]] lowercase__ : int = Union[T, List[T], Dict[str, T]] lowercase__ : List[Any] = Union[str, bytes, os.PathLike]
187
'''simple docstring''' import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class _lowerCamelCase ( lowercase__ ): '''simple docstring''' A_ : Dict = (DDPMScheduler,) def __lowerCAmelCase ( self : Any , **_A : Dict ) -> str: __magic_name__ : str = { 'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'variance_type': 'fixed_small', 'clip_sample': True, } config.update(**_A ) return config def __lowerCAmelCase ( self : str ) -> Union[str, Any]: for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def __lowerCAmelCase ( self : Optional[int] ) -> int: for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_A ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_A ) def __lowerCAmelCase ( self : Any ) -> Tuple: for clip_sample in [True, False]: self.check_over_configs(clip_sample=_A ) def __lowerCAmelCase ( self : Optional[int] ) -> str: self.check_over_configs(thresholding=_A ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_A , prediction_type=_A , sample_max_value=_A , ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def __lowerCAmelCase ( self : Optional[Any] ) -> List[str]: for t in [0, 500, 999]: self.check_over_forward(time_step=_A ) def __lowerCAmelCase ( self : List[str] ) -> Optional[Any]: __magic_name__ : Union[str, Any] = self.scheduler_classes[0] __magic_name__ : Any = self.get_scheduler_config() __magic_name__ : Dict = scheduler_class(**_A ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def __lowerCAmelCase ( self : Tuple ) -> int: __magic_name__ : Tuple = self.scheduler_classes[0] __magic_name__ : Union[str, Any] = self.get_scheduler_config() __magic_name__ : str = scheduler_class(**_A ) __magic_name__ : Any = len(_A ) __magic_name__ : Union[str, Any] = self.dummy_model() __magic_name__ : List[Any] = self.dummy_sample_deter __magic_name__ : Optional[Any] = torch.manual_seed(0 ) for t in reversed(range(_A ) ): # 1. predict noise residual __magic_name__ : Tuple = model(_A , _A ) # 2. predict previous mean of sample x_t-1 __magic_name__ : Union[str, Any] = scheduler.step(_A , _A , _A , generator=_A ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance __magic_name__ : Dict = pred_prev_sample __magic_name__ : Union[str, Any] = torch.sum(torch.abs(_A ) ) __magic_name__ : Dict = torch.mean(torch.abs(_A ) ) assert abs(result_sum.item() - 258.9606 ) < 1E-2 assert abs(result_mean.item() - 0.3372 ) < 1E-3 def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: __magic_name__ : List[Any] = self.scheduler_classes[0] __magic_name__ : List[str] = self.get_scheduler_config(prediction_type='v_prediction' ) __magic_name__ : Any = scheduler_class(**_A ) __magic_name__ : Any = len(_A ) __magic_name__ : Dict = self.dummy_model() __magic_name__ : str = self.dummy_sample_deter __magic_name__ : str = torch.manual_seed(0 ) for t in reversed(range(_A ) ): # 1. predict noise residual __magic_name__ : List[Any] = model(_A , _A ) # 2. predict previous mean of sample x_t-1 __magic_name__ : Tuple = scheduler.step(_A , _A , _A , generator=_A ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance __magic_name__ : List[Any] = pred_prev_sample __magic_name__ : int = torch.sum(torch.abs(_A ) ) __magic_name__ : Any = torch.mean(torch.abs(_A ) ) assert abs(result_sum.item() - 202.0296 ) < 1E-2 assert abs(result_mean.item() - 0.2631 ) < 1E-3 def __lowerCAmelCase ( self : List[str] ) -> str: __magic_name__ : Dict = self.scheduler_classes[0] __magic_name__ : Any = self.get_scheduler_config() __magic_name__ : Optional[Any] = scheduler_class(**_A ) __magic_name__ : List[str] = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_A ) __magic_name__ : List[str] = scheduler.timesteps for i, timestep in enumerate(_A ): if i == len(_A ) - 1: __magic_name__ : Optional[int] = -1 else: __magic_name__ : List[Any] = timesteps[i + 1] __magic_name__ : Union[str, Any] = scheduler.previous_timestep(_A ) __magic_name__ : Any = prev_t.item() self.assertEqual(_A , _A ) def __lowerCAmelCase ( self : Tuple ) -> str: __magic_name__ : str = self.scheduler_classes[0] __magic_name__ : Union[str, Any] = self.get_scheduler_config() __magic_name__ : Union[str, Any] = scheduler_class(**_A ) __magic_name__ : Optional[int] = [100, 87, 50, 51, 0] with self.assertRaises(_A , msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=_A ) def __lowerCAmelCase ( self : Optional[int] ) -> int: __magic_name__ : Union[str, Any] = self.scheduler_classes[0] __magic_name__ : Union[str, Any] = self.get_scheduler_config() __magic_name__ : Union[str, Any] = scheduler_class(**_A ) __magic_name__ : Optional[int] = [100, 87, 50, 1, 0] __magic_name__ : Tuple = len(_A ) with self.assertRaises(_A , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=_A , timesteps=_A ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: __magic_name__ : List[Any] = self.scheduler_classes[0] __magic_name__ : List[str] = self.get_scheduler_config() __magic_name__ : Union[str, Any] = scheduler_class(**_A ) __magic_name__ : Tuple = [scheduler.config.num_train_timesteps] with self.assertRaises( _A , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=_A )
331
0
from __future__ import annotations from PIL import Image # Define glider example lowercase_ = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example lowercase_ = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __lowerCamelCase : List[str] = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __lowerCamelCase : int = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(SCREAMING_SNAKE_CASE__ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(SCREAMING_SNAKE_CASE__ ) - 1: neighbour_count += cells[i + 1][j] if i < len(SCREAMING_SNAKE_CASE__ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __lowerCamelCase : str = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(SCREAMING_SNAKE_CASE__ ) return next_generation def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] for _ in range(SCREAMING_SNAKE_CASE__ ): # Create output image __lowerCamelCase : List[Any] = Image.new('RGB' , (len(cells[0] ), len(SCREAMING_SNAKE_CASE__ )) ) __lowerCamelCase : List[Any] = img.load() # Save cells to image for x in range(len(SCREAMING_SNAKE_CASE__ ) ): for y in range(len(cells[0] ) ): __lowerCamelCase : List[Any] = 255 - cells[y][x] * 255 __lowerCamelCase : Dict = (colour, colour, colour) # Save image images.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = new_generation(SCREAMING_SNAKE_CASE__ ) return images if __name__ == "__main__": lowercase_ = generate_images(GLIDER, 1_6) images[0].save('out.gif', save_all=True, append_images=images[1:])
367
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
194
0
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='''%(message)s''') def SCREAMING_SNAKE_CASE_ ( __magic_name__ : np.ndarray ) -> np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : np.ndarray , __magic_name__ : np.ndarray , __magic_name__ : int ) -> np.ndarray: """simple docstring""" UpperCamelCase :List[str] = np.nan for i in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Tuple = features[:, labels == i] UpperCamelCase :List[str] = data.mean(1 ) # Centralize the data of class i UpperCamelCase :List[Any] = data - column_reshape(SCREAMING_SNAKE_CASE__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(SCREAMING_SNAKE_CASE__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCamelCase :List[str] = np.dot(SCREAMING_SNAKE_CASE__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : np.ndarray , __magic_name__ : np.ndarray , __magic_name__ : int ) -> np.ndarray: """simple docstring""" UpperCamelCase :Optional[int] = features.mean(1 ) UpperCamelCase :Union[str, Any] = np.nan for i in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = features[:, labels == i] UpperCamelCase :List[str] = data.shape[1] UpperCamelCase :Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ ) , (column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCamelCase :Any = device_data * np.dot( column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ ) , (column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : np.ndarray , __magic_name__ : int ) -> np.ndarray: """simple docstring""" if features.any(): UpperCamelCase :Union[str, Any] = features.mean(1 ) # Center the dataset UpperCamelCase :Union[str, Any] = features - np.reshape(SCREAMING_SNAKE_CASE__ , (data_mean.size, 1) ) UpperCamelCase :Union[str, Any] = np.dot(SCREAMING_SNAKE_CASE__ , centered_data.T ) / features.shape[1] UpperCamelCase :List[str] = np.linalg.eigh(SCREAMING_SNAKE_CASE__ ) # Take all the columns in the reverse order (-1), and then takes only the first UpperCamelCase :Union[str, Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space UpperCamelCase :Optional[Any] = np.dot(filtered_eigenvectors.T , SCREAMING_SNAKE_CASE__ ) logging.info("""Principal Component Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=SCREAMING_SNAKE_CASE__ ) logging.error("""Dataset empty""" ) raise AssertionError def SCREAMING_SNAKE_CASE_ ( __magic_name__ : np.ndarray , __magic_name__ : np.ndarray , __magic_name__ : int , __magic_name__ : int ) -> np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: UpperCamelCase :Dict = eigh( covariance_between_classes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , covariance_within_classes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) UpperCamelCase :Optional[int] = eigenvectors[:, ::-1][:, :dimensions] UpperCamelCase :Optional[Any] = np.linalg.svd(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = svd_matrix[:, 0:dimensions] UpperCamelCase :Optional[Any] = np.dot(filtered_svd_matrix.T , SCREAMING_SNAKE_CASE__ ) logging.info("""Linear Discriminant Analysis computed""" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=SCREAMING_SNAKE_CASE__ ) logging.error("""Dataset empty""" ) raise AssertionError def SCREAMING_SNAKE_CASE_ ( ) -> None: """simple docstring""" UpperCamelCase :Union[str, Any] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) UpperCamelCase :Union[str, Any] = np.array([0, 0, 0, 1, 1] ) UpperCamelCase :Tuple = 2 UpperCamelCase :int = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(SCREAMING_SNAKE_CASE__ ) as error_info: UpperCamelCase :Union[str, Any] = linear_discriminant_analysis( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): raise AssertionError( """Did not raise AssertionError for dimensions > classes""" ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE_ ( ) -> None: """simple docstring""" UpperCamelCase :List[Any] = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) UpperCamelCase :Dict = 2 UpperCamelCase :str = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(SCREAMING_SNAKE_CASE__ ) as error_info: UpperCamelCase :str = principal_component_analysis(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
38
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Optional[Any] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Union[str, Any] = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys snake_case_ : str = _LazyModule(__name__, globals()["__file__"], _import_structure)
125
0
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class lowercase_ ( __UpperCamelCase ): UpperCamelCase_ : str = DistilBertTokenizer UpperCamelCase_ : Dict = DistilBertTokenizerFast UpperCamelCase_ : Tuple = True @slow def UpperCamelCase_ ( self : List[str] ) -> List[str]: _snake_case = DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) _snake_case = tokenizer.encode('''sequence builders''' , add_special_tokens=A__ ) _snake_case = tokenizer.encode('''multi-sequence build''' , add_special_tokens=A__ ) _snake_case = tokenizer.build_inputs_with_special_tokens(A__ ) _snake_case = tokenizer.build_inputs_with_special_tokens(A__ , A__ ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
356
import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase_ : def __init__( self : Optional[Any] , A__ : str , A__ : Any=13 , A__ : str=[30, 30] , A__ : int=2 , A__ : Dict=3 , A__ : str=True , A__ : Union[str, Any]=True , A__ : Any=32 , A__ : int=5 , A__ : str=4 , A__ : List[Any]=37 , A__ : Union[str, Any]="gelu" , A__ : Dict=0.1 , A__ : Dict=0.1 , A__ : Tuple=10 , A__ : Dict=0.02 , A__ : Any=3 , A__ : Union[str, Any]=None , A__ : Optional[Any]=8 , A__ : Dict=10 , ) -> Optional[Any]: _snake_case = parent _snake_case = batch_size _snake_case = image_size _snake_case = patch_size _snake_case = num_channels _snake_case = is_training _snake_case = use_labels _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = type_sequence_label_size _snake_case = initializer_range _snake_case = num_labels _snake_case = scope _snake_case = n_targets _snake_case = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens _snake_case = (image_size[1] // patch_size) * (image_size[0] // patch_size) _snake_case = num_patches + 1 + self.num_detection_tokens def UpperCamelCase_ ( self : List[str] ) -> str: _snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) _snake_case = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) _snake_case = [] for i in range(self.batch_size ): _snake_case = {} _snake_case = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=A__ ) _snake_case = torch.rand(self.n_targets , 4 , device=A__ ) labels.append(A__ ) _snake_case = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Dict ) -> List[Any]: return YolosConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A__ , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def UpperCamelCase_ ( self : Any , A__ : Any , A__ : str , A__ : Tuple ) -> Dict: _snake_case = YolosModel(config=A__ ) model.to(A__ ) model.eval() _snake_case = model(A__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , A__ : List[str] , A__ : Optional[Any] , A__ : str ) -> int: _snake_case = YolosForObjectDetection(A__ ) model.to(A__ ) model.eval() _snake_case = model(pixel_values=A__ ) _snake_case = model(A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) _snake_case = model(pixel_values=A__ , labels=A__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def UpperCamelCase_ ( self : Optional[Any] ) -> Tuple: _snake_case = self.prepare_config_and_inputs() _snake_case, _snake_case, _snake_case = config_and_inputs _snake_case = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowercase_ ( __lowercase , __lowercase , unittest.TestCase ): UpperCamelCase_ : Optional[int] = (YolosModel, YolosForObjectDetection) if is_torch_available() else () UpperCamelCase_ : int = ( {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {} ) UpperCamelCase_ : List[str] = False UpperCamelCase_ : List[Any] = False UpperCamelCase_ : List[Any] = False UpperCamelCase_ : Tuple = False def UpperCamelCase_ ( self : Dict , A__ : List[Any] , A__ : List[str] , A__ : Optional[int]=False ) -> Optional[int]: _snake_case = super()._prepare_for_class(A__ , A__ , return_labels=A__ ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": _snake_case = [] for i in range(self.model_tester.batch_size ): _snake_case = {} _snake_case = torch.ones( size=(self.model_tester.n_targets,) , device=A__ , dtype=torch.long ) _snake_case = torch.ones( self.model_tester.n_targets , 4 , device=A__ , dtype=torch.float ) labels.append(A__ ) _snake_case = labels return inputs_dict def UpperCamelCase_ ( self : List[Any] ) -> List[str]: _snake_case = YolosModelTester(self ) _snake_case = ConfigTester(self , config_class=A__ , has_text_modality=A__ , hidden_size=37 ) def UpperCamelCase_ ( self : Optional[int] ) -> Dict: self.config_tester.run_common_tests() def UpperCamelCase_ ( self : List[Any] ) -> str: # YOLOS does not use inputs_embeds pass def UpperCamelCase_ ( self : Union[str, Any] ) -> List[str]: _snake_case, _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = model_class(A__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _snake_case = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A__ , nn.Linear ) ) def UpperCamelCase_ ( self : List[Any] ) -> Optional[Any]: _snake_case, _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = model_class(A__ ) _snake_case = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case = [*signature.parameters.keys()] _snake_case = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A__ ) def UpperCamelCase_ ( self : List[str] ) -> List[Any]: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def UpperCamelCase_ ( self : Union[str, Any] ) -> int: _snake_case, _snake_case = self.model_tester.prepare_config_and_inputs_for_common() _snake_case = True # in YOLOS, the seq_len is different _snake_case = self.model_tester.expected_seq_len for model_class in self.all_model_classes: _snake_case = True _snake_case = False _snake_case = True _snake_case = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): _snake_case = model(**self._prepare_for_class(A__ , A__ ) ) _snake_case = outputs.attentions self.assertEqual(len(A__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _snake_case = True _snake_case = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): _snake_case = model(**self._prepare_for_class(A__ , A__ ) ) _snake_case = outputs.attentions self.assertEqual(len(A__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _snake_case = len(A__ ) # Check attention is always last and order is fine _snake_case = True _snake_case = True _snake_case = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): _snake_case = model(**self._prepare_for_class(A__ , A__ ) ) _snake_case = 1 self.assertEqual(out_len + added_hidden_states , len(A__ ) ) _snake_case = outputs.attentions self.assertEqual(len(A__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def UpperCamelCase_ ( self : int ) -> Dict: def check_hidden_states_output(A__ : Optional[int] , A__ : Union[str, Any] , A__ : int ): _snake_case = model_class(A__ ) model.to(A__ ) model.eval() with torch.no_grad(): _snake_case = model(**self._prepare_for_class(A__ , A__ ) ) _snake_case = outputs.hidden_states _snake_case = getattr( self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(A__ ) , A__ ) # YOLOS has a different seq_length _snake_case = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _snake_case, _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = True check_hidden_states_output(A__ , A__ , A__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _snake_case = True check_hidden_states_output(A__ , A__ , A__ ) def UpperCamelCase_ ( self : Optional[Any] ) -> str: _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*A__ ) @slow def UpperCamelCase_ ( self : List[str] ) -> Dict: for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = YolosModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) def snake_case_() -> str: """simple docstring""" _snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowercase_ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self : Any ) -> str: return AutoImageProcessor.from_pretrained('''hustvl/yolos-small''' ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Tuple ) -> str: _snake_case = YolosForObjectDetection.from_pretrained('''hustvl/yolos-small''' ).to(A__ ) _snake_case = self.default_image_processor _snake_case = prepare_img() _snake_case = image_processor(images=A__ , return_tensors='''pt''' ).to(A__ ) # forward pass with torch.no_grad(): _snake_case = model(inputs.pixel_values ) # verify outputs _snake_case = torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , A__ ) _snake_case = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] , device=A__ , ) _snake_case = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] , device=A__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , A__ , atol=1e-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , A__ , atol=1e-4 ) ) # verify postprocessing _snake_case = image_processor.post_process_object_detection( A__ , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] _snake_case = torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861] ).to(A__ ) _snake_case = [75, 75, 17, 63, 17] _snake_case = torch.tensor([335.0609, 79.3848, 375.4216, 187.2495] ).to(A__ ) self.assertEqual(len(results['''scores'''] ) , 5 ) self.assertTrue(torch.allclose(results['''scores'''] , A__ , atol=1e-4 ) ) self.assertSequenceEqual(results['''labels'''].tolist() , A__ ) self.assertTrue(torch.allclose(results['''boxes'''][0, :] , A__ ) )
278
0
'''simple docstring''' import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def lowerCamelCase ( UpperCAmelCase__ : Optional[int] ) -> Dict: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def lowerCamelCase ( ) -> List[str]: with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" lowercase_ : Any = [1, 2, 3] with pytest.raises(UpperCAmelCase__ ): with parallel_backend("""unsupported backend""" ): map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=2 ) with pytest.raises(UpperCAmelCase__ ): with parallel_backend("""unsupported backend""" ): map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" , [2, -1] ) def lowerCamelCase ( UpperCAmelCase__ : int ) -> Union[str, Any]: lowercase_ : str = [1, 2] lowercase_ : Union[str, Any] = {"""a""": 1, """b""": 2} lowercase_ : str = {"""a""": [1, 2], """b""": [3, 4]} lowercase_ : List[str] = {"""a""": {"""1""": 1}, """b""": 2} lowercase_ : Optional[int] = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} lowercase_ : Union[str, Any] = [2, 3] lowercase_ : Optional[int] = {"""a""": 2, """b""": 3} lowercase_ : Union[str, Any] = {"""a""": [2, 3], """b""": [4, 5]} lowercase_ : Optional[Any] = {"""a""": {"""1""": 2}, """b""": 3} lowercase_ : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=UpperCAmelCase__ ) == expected_map_nested_sa assert map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=UpperCAmelCase__ ) == expected_map_nested_sa assert map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=UpperCAmelCase__ ) == expected_map_nested_sa assert map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=UpperCAmelCase__ ) == expected_map_nested_sa assert map_nested(UpperCAmelCase__ , UpperCAmelCase__ , num_proc=UpperCAmelCase__ ) == expected_map_nested_sa
239
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class __magic_name__ : def __init__( self : Any ): lowercase_ : list[Any] = [] lowercase_ : int = 0 lowercase_ : int = 0 def SCREAMING_SNAKE_CASE_ ( self : int ): return self.head == self.tail def SCREAMING_SNAKE_CASE_ ( self : List[str] , lowercase_ : Any ): self.data.append(lowercase_ ) lowercase_ : Optional[Any] = self.tail + 1 def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): lowercase_ : List[Any] = self.data[self.head] lowercase_ : Optional[int] = self.head + 1 return ret def SCREAMING_SNAKE_CASE_ ( self : List[str] ): return self.tail - self.head def SCREAMING_SNAKE_CASE_ ( self : Tuple ): print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class __magic_name__ : def __init__( self : Any , lowercase_ : Any ): lowercase_ : Optional[Any] = data lowercase_ : MyNode | None = None lowercase_ : MyNode | None = None lowercase_ : int = 1 def SCREAMING_SNAKE_CASE_ ( self : Tuple ): return self.data def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): return self.left def SCREAMING_SNAKE_CASE_ ( self : Dict ): return self.right def SCREAMING_SNAKE_CASE_ ( self : str ): return self.height def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any ): lowercase_ : Dict = data def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , lowercase_ : MyNode | None ): lowercase_ : Optional[Any] = node def SCREAMING_SNAKE_CASE_ ( self : Tuple , lowercase_ : MyNode | None ): lowercase_ : str = node def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : int ): lowercase_ : Tuple = height def lowerCamelCase ( UpperCAmelCase__ : MyNode | None ) -> int: if node is None: return 0 return node.get_height() def lowerCamelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> int: if a > b: return a return b def lowerCamelCase ( UpperCAmelCase__ : MyNode ) -> MyNode: print("""left rotation node:""" , node.get_data() ) lowercase_ : Union[str, Any] = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(UpperCAmelCase__ ) lowercase_ : Any = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(UpperCAmelCase__ ) lowercase_ : Optional[int] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(UpperCAmelCase__ ) return ret def lowerCamelCase ( UpperCAmelCase__ : MyNode ) -> MyNode: print("""right rotation node:""" , node.get_data() ) lowercase_ : Dict = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(UpperCAmelCase__ ) lowercase_ : Tuple = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(UpperCAmelCase__ ) lowercase_ : str = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(UpperCAmelCase__ ) return ret def lowerCamelCase ( UpperCAmelCase__ : MyNode ) -> MyNode: lowercase_ : Optional[Any] = node.get_left() assert left_child is not None node.set_left(left_rotation(UpperCAmelCase__ ) ) return right_rotation(UpperCAmelCase__ ) def lowerCamelCase ( UpperCAmelCase__ : MyNode ) -> MyNode: lowercase_ : Optional[Any] = node.get_right() assert right_child is not None node.set_right(right_rotation(UpperCAmelCase__ ) ) return left_rotation(UpperCAmelCase__ ) def lowerCamelCase ( UpperCAmelCase__ : MyNode | None , UpperCAmelCase__ : Any ) -> MyNode | None: if node is None: return MyNode(UpperCAmelCase__ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , UpperCAmelCase__ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected lowercase_ : List[Any] = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child lowercase_ : List[Any] = right_rotation(UpperCAmelCase__ ) else: lowercase_ : Any = lr_rotation(UpperCAmelCase__ ) else: node.set_right(insert_node(node.get_right() , UpperCAmelCase__ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: lowercase_ : Any = node.get_right() assert right_child is not None if data < right_child.get_data(): lowercase_ : Optional[int] = rl_rotation(UpperCAmelCase__ ) else: lowercase_ : Optional[int] = left_rotation(UpperCAmelCase__ ) lowercase_ : Optional[int] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(UpperCAmelCase__ ) return node def lowerCamelCase ( UpperCAmelCase__ : MyNode ) -> Any: while True: lowercase_ : Any = root.get_right() if right_child is None: break lowercase_ : List[str] = right_child return root.get_data() def lowerCamelCase ( UpperCAmelCase__ : MyNode ) -> Any: while True: lowercase_ : List[Any] = root.get_left() if left_child is None: break lowercase_ : str = left_child return root.get_data() def lowerCamelCase ( UpperCAmelCase__ : MyNode , UpperCAmelCase__ : Any ) -> MyNode | None: lowercase_ : Union[str, Any] = root.get_left() lowercase_ : int = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: lowercase_ : Any = get_left_most(UpperCAmelCase__ ) root.set_data(UpperCAmelCase__ ) root.set_right(del_node(UpperCAmelCase__ , UpperCAmelCase__ ) ) elif left_child is not None: lowercase_ : Dict = left_child elif right_child is not None: lowercase_ : Dict = right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(UpperCAmelCase__ , UpperCAmelCase__ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(UpperCAmelCase__ , UpperCAmelCase__ ) ) if get_height(UpperCAmelCase__ ) - get_height(UpperCAmelCase__ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): lowercase_ : str = left_rotation(UpperCAmelCase__ ) else: lowercase_ : List[str] = rl_rotation(UpperCAmelCase__ ) elif get_height(UpperCAmelCase__ ) - get_height(UpperCAmelCase__ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): lowercase_ : Optional[Any] = right_rotation(UpperCAmelCase__ ) else: lowercase_ : List[str] = lr_rotation(UpperCAmelCase__ ) lowercase_ : int = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(UpperCAmelCase__ ) return root class __magic_name__ : def __init__( self : List[str] ): lowercase_ : MyNode | None = None def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): return get_height(self.root ) def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any ): print("""insert:""" + str(lowercase_ ) ) lowercase_ : Dict = insert_node(self.root , lowercase_ ) def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any ): print("""delete:""" + str(lowercase_ ) ) if self.root is None: print("""Tree is empty!""" ) return lowercase_ : int = del_node(self.root , lowercase_ ) def __str__( self : Optional[int] , ): # a level traversale, gives a more intuitive look on the tree lowercase_ : int = """""" lowercase_ : Optional[int] = MyQueue() q.push(self.root ) lowercase_ : Optional[Any] = self.get_height() if layer == 0: return output lowercase_ : Optional[int] = 0 while not q.is_empty(): lowercase_ : Any = q.pop() lowercase_ : List[Any] = """ """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(lowercase_ ) q.push(lowercase_ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space lowercase_ : Union[str, Any] = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , lowercase_ ) - 1: lowercase_ : Optional[Any] = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def lowerCamelCase ( ) -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() _lowercase : Optional[Any] = AVLtree() _lowercase : Optional[Any] = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
239
1
def UpperCamelCase ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" while a != 0: lowercase__ , lowercase__ = b % a, a return b def UpperCamelCase ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" if gcd(__magic_name__ , __magic_name__ ) != 1: lowercase__ = f'''mod inverse of {a!r} and {m!r} does not exist''' raise ValueError(__magic_name__ ) lowercase__ , lowercase__ , lowercase__ = 1, 0, a lowercase__ , lowercase__ , lowercase__ = 0, 1, m while va != 0: lowercase__ = ua // va lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
146
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A : List[Any] = logging.get_logger(__name__) class A ( UpperCAmelCase__ ): '''simple docstring''' def __init__(self : List[Any] , *_UpperCAmelCase : int , **_UpperCAmelCase : List[str] ) -> None: """simple docstring""" warnings.warn( """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use CLIPImageProcessor instead.""" , _UpperCAmelCase , ) super().__init__(*_UpperCAmelCase , **_UpperCAmelCase )
146
1